一種方法是使用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 FileMonitor從PyGTK/PyGObject。您可以使用GIO.File的monitor_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()
太假,無法真正幫助。無論如何,要監視新文件的目錄,您可以在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
沒有什麼可說的。它非常基本。我真的只是在尋找一種方法來等待文件被創建,而無需使用cpu(因此可以創建它們)。 – xZel 2010-08-05 17:53:22