进行非阻塞等待的一种方法是使用线程.事件 http://docs.python.org/library/threading.html#event-objects:
import threading
dummy_event = threading.Event()
dummy_event.wait(timeout=1)
这可以是set()
来自另一个线程来指示某件事已经完成。But如果您在另一个线程中执行操作,则可以完全避免超时和事件,只需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()
方法。
如果您正在等待其他进程完成,那么最好使用您自己的脚本来管理它们子流程 http://docs.python.org/library/subprocess.html模块(然后,例如,使用wait http://docs.python.org/library/subprocess.html#subprocess.Popen.wait方法以确保在进行进一步工作之前完成该过程)。
如果您无法从脚本中管理子进程,但您知道 PID,则可以使用os.waitpid() http://docs.python.org/library/os.html#os.waitpid功能。当心OSError
如果在您使用此功能时该过程已经完成...
如果您想要一种跨平台的方式来观看目录以获取新文件的通知,我建议使用GIO文件监视器 http://library.gnome.org/devel/pygobject/stable/class-giofilemonitor.html from PyGTK/PyGObject http://library.gnome.org/devel/pygobject/stable/。您可以使用以下命令获取目录上的监视器监控目录 http://library.gnome.org/devel/pygobject/stable/class-giofile.html#method-giofile--monitor-directory的方法GIO.File http://library.gnome.org/devel/pygobject/stable/class-giofile.html.
目录监视的快速示例代码:
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()