我想在多线程python程序的每个线程中执行一个外部程序。
假设最大运行时间设置为 1 秒。如果启动的进程在 1 秒内完成,主程序将捕获其输出以供进一步处理。如果它没有在 1 秒内完成,主程序就终止它并启动另一个新进程。
如何实现?
最佳答案
您可以定期轮询它:
import subprocess, time
s = subprocess.Popen(['foo', 'args'])
timeout = 1
poll_period = 0.1
s.poll()
while s.returncode is None and timeout > 0:
time.sleep(poll_period)
timeout -= poll_period
s.poll()
if timeout <= 0:
s.kill() # timed out
else:
pass # completed
然后您可以将上面的代码放入函数中并将其作为线程启动。
关于python - 以指定的最大运行时间运行外部程序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2983963/