[ Python module threading as daemon with logging ]
I try to create an init and a mydeamon module in Python 2.7, under Debian 7
The init check the required things (db connection etc) and run mydaemon in a thread. mydeamon check db do things and write a logfile.
The problem when set the thread daemon the logging and function call fail. But if the thread not daemon working fine...
Can you help where I wrong or what will be a better approach.
init.py
import mydaemon, threading
print 'start'
t = threading.Thread( target = mydaemon.start, args = () )
t.daemon = True # error here
t.start()
mydaemon.py
import logging
def start():
work()
return
def work():
logging.basicConfig( filename = 'mylog.log', level = logging.DEBUG )
logging.info('foo log')
print 'foo console'
return
Answer 1
Making it as a deamon means the background thread dies as soon as the main app closes. Your code 'works' as is, simply add a pause to init.py to model this behavior:
...
t.start()
import time
time.sleep(1)
This is discussed in more detail at http://pymotw.com/2/threading/#daemon-vs-non-daemon-threads.
The simply way to fix this is to join the thread.
import mydaemon, threading
print 'start'
t = threading.Thread( target = mydaemon.start, args = () )
t.daemon = True # error here
t.start()
t.join()
Answer 2
My collage found another method with external Daemon module (python-daemon)
http://www.gavinj.net/2012/06/building-python-daemon-process.html
In the tutorial have some error but read comments ;-)