Skip to content

Instantly share code, notes, and snippets.

@fish2000
Created September 30, 2010 06:06
Show Gist options
  • Save fish2000/604108 to your computer and use it in GitHub Desktop.
Save fish2000/604108 to your computer and use it in GitHub Desktop.
python windows cron-ish screenshot service example
#!/usr/bin/env python
# encoding: utf-8
"""
autoshot.py
Extend the Windows Service to do a real task
(the PIL call did not work here, hence the entirely
separate oneshot.py script)
Created by fish on 2009-12-08.
Copyright (c) 2009 __MyCompanyName__. All rights reserved.
"""
import sys, os
import time
import datetime
import PIL.Image
import ImageGrab
import PngImagePlugin
import GifImagePlugin
import win32serviceutil
import winservice
class ShotService(winservice.Service):
_svc_name_ = 'AutoShot'
_svc_display_name_ = 'Automatic Screenshotter'
def start(self):
pass
def stop(self):
pass
def do_run(self):
self.screenshot()
def screenshot(self, *args, **kwargs):
outcmd = "C:\Python26\pythonw26.exe \"C:\\Documents and Settings\\Raphael Lemkin\\My Documents\\My Dropbox\\lemkin-web\\_installationtools\\autoshot\\oneshot.py\""
self.log("ShotService::screenshot(): %s" % outcmd)
os.system(outcmd)
def main():
win32serviceutil.HandleCommandLine(ShotService)
if __name__ == '__main__':
main()
#!/usr/bin/env python
# encoding: utf-8
"""
oneshot.py
Take a screenshot on Windows
Created by fish on 2009-12-08.
Copyright (c) 2009 __MyCompanyName__. All rights reserved.
"""
import sys
import os
import sys
import os
import time
import datetime
import PIL.Image
import ImageGrab
import PngImagePlugin
import GifImagePlugin
def main():
savepath = 'C:\Documents and Settings\Raphael Lemkin\My Documents\My Dropbox\lemkin-web\SHOTS'
nameformat = "%Y%m%d.%H.%M.%S"
filetype = "png"
sleeptime = 1
rightnow = datetime.datetime.now()
shotfile = "%s.%s" % (rightnow.strftime(nameformat), filetype)
im = ImageGrab.grab()
shotout = open(os.path.join(savepath, shotfile), 'wb')
im.save(shotout, 'PNG', optimize=True)
shotout.close()
if __name__ == '__main__':
main()
#!/usr/bin/env python
# encoding: utf-8
"""
winservice.py
I forget where I got this base class ... activestate?
probably activestate.
Anyway, don't ever write a windows service in python.
Don't ever write a windows service period, in fact --
I'd wager it's easier to port Vixie crond to windows
than deal with "services" and the associated arcane
inanity.
Created by fish on 2009-12-08.
Copyright (c) 2009 __MyCompanyName__. All rights reserved.
"""
from os.path import splitext, abspath
from sys import modules
import win32serviceutil
import win32service
import win32event
import win32api
class Service(win32serviceutil.ServiceFramework):
_svc_name_ = '_unNamed'
_svc_display_name_ = '_Service Template'
_timeout = 60000
def __init__(self, *args):
win32serviceutil.ServiceFramework.__init__(self, *args)
self.log('init')
self.stop_event = win32event.CreateEvent(None, 0, 0, None)
def log(self, msg):
import servicemanager
servicemanager.LogInfoMsg(str(msg))
def sleep(self, sec):
win32api.Sleep(sec*1000, True)
def SvcDoRun(self):
self.ReportServiceStatus(win32service.SERVICE_START_PENDING)
try:
self.ReportServiceStatus(win32service.SERVICE_RUNNING)
self.log('start')
self.start()
self.log('wait')
#win32event.WaitForSingleObject(self.stop_event, win32event.INFINITE)
while (1):
self.log("STARTING RUNLOOP --")
rc = win32event.WaitForSingleObject(self.stop_event, self._timeout)
if (rc == win32event.WAIT_OBJECT_0):
self.log("STOP SIGNAL")
break
else:
self.do_run()
self.log('done')
except Exception, x:
self.log('Exception : %s' % x)
self.SvcStop()
def SvcStop(self):
self.ReportServiceStatus(win32service.SERVICE_STOP_PENDING)
self.log('stopping')
self.stop()
self.log('stopped')
win32event.SetEvent(self.stop_event)
self.ReportServiceStatus(win32service.SERVICE_STOPPED)
# to be overridden
def start(self): pass
# to be overridden
def stop(self): pass
# to be overridden
def do_run(self): pass
def instart(cls, name, display_name=None, stay_alive=True):
'''
Install and Start (auto) a Service
cls : the class (derived from Service) that implement the Service
name : Service name
display_name : the name displayed in the service manager
stay_alive : Service will stop on logout if False
'''
cls._svc_name_ = name
cls._svc_display_name_ = display_name or name
try:
module_path=modules[cls.__module__].__file__
except AttributeError:
# maybe py2exe went by
from sys import executable
module_path=executable
module_file=splitext(abspath(module_path))[0]
cls._svc_reg_class_ = '%s.%s' % (module_file, cls.__name__)
if stay_alive: win32api.SetConsoleCtrlHandler(lambda x: True, True)
try:
win32serviceutil.InstallService(
cls._svc_reg_class_,
cls._svc_name_,
cls._svc_display_name_,
startType=win32service.SERVICE_AUTO_START
)
print 'Install ok'
win32serviceutil.StartService(
cls._svc_name_
)
print 'Start ok'
except Exception, x:
print str(x)
#!/usr/bin/env python
# encoding: utf-8
"""
winservice_test.py
Windows Service tester
Created by fish on 2009-12-08.
Copyright (c) 2009 __MyCompanyName__. All rights reserved.
"""
from winservice import Service, instart
class Test(Service):
def start(self):
self.runflag=True
while self.runflag:
self.sleep(10)
self.log("I'm alive ...")
def stop(self):
self.runflag=False
self.log("I'm done")
instart(Test, 'aTest', 'Python Service Test')
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment