2014-04-24 34 views
1

背景,我需要工作,這個腳本在像守護進程的背景下,到現在我只可以把它做的工作,但不是在後臺:守護在蟒蛇

import threading 
from time import gmtime, strftime 
import time 


def write_it(): 
    #this function write the actual time every 2 seconds in a file 
    threading.Timer(2.0, write_it).start() 
    f = open("file.txt", "a") 
    hora = strftime("%Y-%m-%d %H:%M:%S", gmtime()) 
    #print hora 
    f.write(hora+"\n") 
    f.close() 

def non_daemon(): 
    time.sleep(5) 
    #print 'Test non-daemon' 
    write_it() 

t = threading.Thread(name='non-daemon', target=non_daemon) 

t.start() 

我已經嘗試過其他方法,但沒有他們的工作,我在尋找背景,還有其他的選擇嗎?

+2

守護進程在這種情況下意味着什麼?您是否需要在後臺運行應用程序,或者您希望'write_it()'在後臺運行「,而您的應用程序執行其他操作? – msvalkon

+0

這個想法是守護進程write_it()並能夠做其他事情 –

+0

究竟是什麼問題?該線程正在後臺運行,並且您可以繼續運行代碼。 – sdamashek

回答

1

如果您希望將腳本作爲守護進程運行,一種好的方法是使用Python Daemon庫。下面的代碼應該做你正在尋找實現的目標:

import daemon 
import time 

def write_time_to_file(): 
    with open("file.txt", "a") as f: 
     hora = time.strftime("%Y-%m-%d %H:%M:%S", time.gmtime()) 
     f.write(hora+"\n") 

with daemon.DaemonContext(): 
    while(True): 
     write_time_to_file() 
     time.sleep(2) 

本地測試這一點,它工作得很好,追加一次文件每2秒。

+0

謝謝,我試過了,它在後臺運行,但它不會追加任何東西:/ –

+0

你剛纔運行了我自己編寫的代碼對於我來自python shell)還是你把它包裝在別的東西來執行? – robjohncox