python time sleep多线程,Python中的time.sleep和多线程问题

I am having an issue with the time.sleep() function in python. I am running a script that needs to wait for another program to generate txt files. Although, this is a terribly old machine, so when I sleep the python script, I run into issues with the other program not generating files. Is there any alternatives to using time.sleep()? I thought locking the thread might work but essentially it would just be a loop of locking the thread for a couple of seconds. I'll give some pseudo code here of what I'm doing.

While running:

if filesFound != []:

moveFiles

else:

time.sleep(1)

解决方案

One way to do a non-blocking wait is to use threading.Event:

import threading

dummy_event = threading.Event()

dummy_event.wait(timeout=1)

This can be set() from another thread to indicate that something has completed. But if you are doing stuff in another thread, you could avoid the timeout and event altogether and just join the other thread:

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

If you want an example of using events for more fine-grained control, I can show you that...

The threading approach won't work if your platform doesn't provide the threading module. For example, if you try to substitute the dummy_threading module, dummy_event.wait() returns immediately. Not sure about the join() approach.

If you are waiting for other processes to finish, you would be better off managing them from your own script using the subprocess module (and then, for example, using the wait method to be sure the process is done before you do further work).

If you can't manage the subprocess from your script, but you know the PID, you can use the os.waitpid() function. Beware of the OSError if the process has already finished by the time you use this function...

If you want a cross-platform way to watch a directory to be notified of new files, I'd suggest using a GIO FileMonitor from PyGTK/PyGObject. You can get a monitor on a directory using the monitor_directory method of a GIO.File.

Quick sample code for a directory watch:

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()

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值