[英]Python module threading as daemon with logging
我正在嘗試在Debian 7下的Python 2.7中創建模塊init
和模塊mydaemon
。
模塊init
檢查諸如數據庫連接之類的要求。然后, mydaemon
在線程中運行,並使用數據庫來做事並編寫日志文件。
設置線程守護程序時的問題是日志記錄和函數調用失敗。 但是如果線程沒有守護程序正常工作...
我在哪里錯了?有什么更好的方法?
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
將其設置為守護進程意味着后台線程在主應用程序關閉時立即死亡。 您的代碼按原樣“工作”,只需在init.py中添加一個暫停即可對這種行為進行建模:
...
t.start()
import time
time.sleep(1)
有關詳細信息,請參見http://pymotw.com/2/threading/#daemon-vs-non-daemon-threads 。
解決此問題的簡單方法是加入線程。
import mydaemon, threading
print 'start'
t = threading.Thread( target = mydaemon.start, args = () )
t.daemon = True # error here
t.start()
t.join()
我的拼貼找到了另一種使用外部守護程序模塊(python-daemon)的方法
http://www.gavinj.net/2012/06/building-python-daemon-process.html
在教程中有一些錯誤,但請閱讀注釋;-)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.