如何在 Python 中执行命令行程序时超时



我正在从Python执行Maple,如果超过最长时间,我想停止程序。如果是 Python 函数,则可以使用超时装饰器来完成。但是我不确定如何为命令行调用执行此操作。这是伪代码

import os
import timeit as tt
t1 = tt.default_timer()
os.system('echo path_to_maple params')
t2 = tt.default_timer()
dt = t2 - t1

只是为了这个程序的时间,一切正常。但是 maple 程序需要很多时间,所以我想定义一个 maxtime,检查 t1 是否<maxtime,然后让程序执行其他没有,即将脚本更改为这样的内容:>

import sys
maxtime = 10 # seconds
t1 = tt.default_timer()
if (t1 < maxtime):
   os.system('echo path_to_maple params')
    t2 = tt.default_timer()
    dt = t2 - t1
else:
    sys.exit('Timeout')

目前这不起作用。有没有更好的方法可以做到这一点?

您可以使用

subprocess.Popen生成子进程。确保正确处理标准输出和标准输出。然后使用Popen.wait(timeout)调用并在TimeoutExpired到达时终止进程。

使用 subprocess.Popen() 来执行出价,如果您使用的是 3.3 之前的 Python 版本,则必须自己处理超时,因此:

import subprocess
import sys
import time
# multi-platform precision clock
get_timer = time.clock if sys.platform == "win32" else time.time
timeout = 10  # in seconds
# don't forget to set STDIN/STDERR handling if you need them...
process = subprocess.Popen(["maple", "args", "and", "such"])
current_time = get_timer()
while get_timer() < current_time + timeout and process.poll() is None:
    time.sleep(0.5)  # wait half a second, you can adjust the precision
if process.poll() is None:  # timeout expired, if it's still running...
    process.terminate()  # TERMINATE IT! :D

在 Python 3.3+ 中,它就像调用一样简单: subprocess.run(["maple", "args", "and", "such"], timeout=10)

我认为

您可以使用

threading.Timer(TIME, function , args=(,))

在延迟后执行函数

最新更新