2014-02-05 53 views
0

守護我試圖創建一個初始化,並在Python 2.7 mydeamon模塊,Debian的7下Python模塊線程與記錄

初始化檢查所需的東西(數據庫連接等),並在一個線程中運行mydaemon。 mydeamon檢查數據庫做事情,並寫一個日誌文件。

設置線程守護進程日誌記錄和函數調用失敗時的問題。 但是,如果線程不守護進程正常工作...

你能幫助我在哪裏錯了或什麼是更好的方法。

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 

回答

0

使得它作爲一個守護進程意味着後臺線程只要主應用程序關閉死亡。您的代碼「作品」原樣,只需添加一個暫停來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() 
+0

嗨,記錄仍然失敗,但文件已創建。 – sheepy

+0

啊,對不起,在沒有debian的windows系統上試過這個。這個問題是因爲當它作爲一個線程被創建時,線程將在主程序死亡後立即死亡。所以它沒有足夠的時間在主程序存在之前寫入文件。我會更新我的答案。 – CasualDemon