运行具有指定最大运行时间的外部程序

jac*_*ack 4 python multithreading subprocess

我想在多线程python程序的每个线程中执行外部程序.

假设最大运行时间设置为1秒.如果启动过程在1秒内完成,则主程序捕获其输出以进行进一步处理.如果它没有在1秒内完成,主程序只是终止它并启动另一个新进程.

怎么实现这个?

Liq*_*ire 6

你可以定期轮询它:

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

然后,您可以将上面的内容放在一个函数中,然后将其作为一个线程启动.