我在python中的time.sleep()函数遇到问题.我正在运行一个脚本,该脚本需要等待另一个程序来生成txt文件.虽然,这是一台非常古老的机器,所以当我休眠python脚本时,我遇到了其他程序无法生成文件的问题.除了使用time.sleep(),还有其他选择吗?我认为锁定线程可能会起作用,但本质上,这只是将线程锁定几秒钟的循环.在这里,我将给出一些我正在做的伪代码.
While running:
if filesFound != []:
moveFiles
else:
time.sleep(1)
解决方法:
进行非阻塞等待的一种方法是使用threading.Event:
import threading
dummy_event = threading.Event()
dummy_event.wait(timeout=1)
可以从另一个线程进行set()来指示已完成某些操作.但是,如果您要在另一个线程中执行操作,则可以完全避免超时和事件,而只需加入另一个线程即可:
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.
目录监视的快速示例代码:
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()
标签:multithreading,python