问题描述
限时送ChatGPT账号..我正在从 Python 执行 Maple,如果程序超过最大时间,我想停止该程序.如果它是一个 Python 函数,这可以通过使用超时装饰器来完成.但我不确定如何为命令行调用执行此操作.这是伪代码
I am executing Maple from Python and would like to stop the program if it exceeds a maximum time. If its a Python function this can be done by using a timeout-decorator. But I am not sure how to do it for command line calls. Here is the pseudocode
import os
import timeit as tt
t1 = tt.default_timer()
os.system('echo path_to_maple params')
t2 = tt.default_timer()
dt = t2 - t1
只是为了计时这个程序,一切正常.然而,枫树程序需要很多时间,所以我想定义一个maxtime,检查是否 t1 <;maxtime 然后让程序执行否则没有.即将脚本更改为如下所示:
Just to time this program, all works fine. However the maple program takes a lot of time so I would like to define a maxtime, check whether t1 < maxtime then let program execute else no. i.e. change the script to something like this:
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')
目前这不起作用.有没有更好的方法来做到这一点?
At the moment this is not working. Is there a better way to do this?
推荐答案
您可以使用 subprocess.Popen
生成子进程.确保正确处理 stdout 和 stderr.然后使用 Popen.wait(timeout)
在 TimeoutExpired<时调用并终止进程/code> 到达.
这篇关于在 Python 中执行命令行程序时如何超时?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
更多推荐
[db:关键词]
发布评论