python - 以指定的最大运行时间运行外部程序

标签 python multithreading subprocess

我想在多线程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/

相关文章:

python - Django:如何过滤和显示页面上类别的帖子

在多线程信号处理程序中调用 fflush?

python - Popen 包含需要对所有输出说是的命令

Python 嵌套循环不会继续子进程

python - 为什么在使用 subprocess.call() 时,我在这个简单的 Python-CGI 上不断收到错误 500?

python - IPython 手动迭代主循环?

python - 何时在 python 中应用(pd.to_numeric)和何时 astype(np.float64)?

python - 如何为点击处理的参数列表指定默认值?

c++ - _beginthread 在父构造函数中

multithreading - node.js 是否在内部使用线程/线程池?