Python中time.sleep和Multithreading的问题

xZe*_*Zel 3 python multithreading

我在python中遇到time.sleep()函数的问题.我正在运行一个脚本,需要等待另一个程序生成txt文件.虽然,这是一个非常古老的机器,所以当我睡眠python脚本时,我遇到了其他程序不生成文件的问题.有没有其他方法可以使用time.sleep()?我认为锁定线程可能会起作用,但实质上它只是一个锁定线程几秒钟的循环.我会在这里给出一些我正在做的伪代码.

While running:
    if filesFound != []:
         moveFiles
    else:
       time.sleep(1)
Run Code Online (Sandbox Code Playgroud)

det*_*tly 7

执行非阻塞等待的一种方法是使用threading.Event:

import threading
dummy_event = threading.Event()
dummy_event.wait(timeout=1)
Run Code Online (Sandbox Code Playgroud)

这可以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
Run Code Online (Sandbox Code Playgroud)

如果你想要一个使用事件进行更精细控制的例子,我可以告诉你......

如果您的平台不提供线程模块,则线程方法将不起作用.例如,如果您尝试替换dummy_threading模块,则dummy_event.wait()立即返回.不确定这种join()方法.

如果您正在等待其他进程完成,那么最好使用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()
Run Code Online (Sandbox Code Playgroud)