2010-08-05 61 views
3

python中的time.sleep()函數存在問題。我正在運行一個腳本,需要等待另一個程序生成txt文件。雖然這是一臺非常古老的機器,所以當我睡覺python腳本時,遇到了其他程序不生成文件的問題。有沒有其他方法可以使用time.sleep()?我認爲鎖定線程可能會工作,但實質上它只是一個鎖定線程幾秒鐘的循環。我會在這裏給我一些僞代碼。Python中的time.sleep和多線程問題

While running: 
    if filesFound != []: 
     moveFiles 
    else: 
     time.sleep(1) 
+5

太假,無法真正幫助。無論如何,要監視新文件的目錄,您可以在Windows中使用pyinotify,http://trac.dbzteam.org/pyinotify,「ReadDirectoryChangesW」(例如,請參閱http://tech-artists.org/wiki/Python_Recipes# Watch_a_Directory_for_Changes)等等。 – 2010-08-05 15:22:28

+0

沒有什麼可說的。它非常基本。我真的只是在尋找一種方法來等待文件被創建,而無需使用cpu(因此可以創建它們)。 – xZel 2010-08-05 17:53:22

回答

7

一種方法是使用threading.Event

import threading 
dummy_event = threading.Event() 
dummy_event.wait(timeout=1) 

這一點可以從另一個線程set()表明某件事已經完成。 如果你是在另一個線程做的東西,你能避免超時和事件完全和公正join其他線程:

import threading 

def create_the_file(completion_event): 
    # Do stuff to create the file 

def Main(): 
    worker = threading.Thread(target=create_the_file) 
    worker.start() 

    # We will stop here until the "create_the_file" function finishes 
    worker.join() 

    # Do stuff with the file 

如果你想使用事件更細粒度的控制的一個例子,我可以告訴你......

如果你的平臺沒有提供線程模塊,線程方法將不起作用。例如,如果您嘗試替換dummy_threading模塊,則立即返回dummy_event.wait()。不確定關於join()的方法。

如果您正在等待其他進程完成,那麼最好使用subprocess模塊從您自己的腳本管理它們(然後,例如使用wait方法確保在執行之前完成該過程進一步的工作)。

如果您不能從腳本管理子流程,但知道PID,則可以使用os.waitpid()函數。如果在使用此功能時已經完成處理,請注意OSError ...

如果您希望以跨平臺的方式觀看要通知新文件的目錄,我建議您使用GIO FileMonitorPyGTK/PyGObject。您可以使用GIO.Filemonitor_directory方法在目錄上獲得監視器。對於目錄表

快速示例代碼:

import gio 

def directory_changed(monitor, file1, file2, evt_type): 
    print "Changed:", file1, file2, evt_type 

gfile = gio.File(".") 
monitor = gfile.monitor_directory(gio.FILE_MONITOR_NONE, None) 
monitor.connect("changed", directory_changed) 

import glib 
ml = glib.MainLoop() 
ml.run() 
-3

檢查標準庫中「subprocess」模塊的文檔。 在那裏的Popen類允許處理你調用的任何子過程的各種方式。當你發現如何正確使用子進程時,你可能甚至不需要使用線程。

的docuemntation是模塊本身中,您只需要做做非阻塞等待

import subprocess 
help(subprocess)