2017-06-13 174 views
0

我正在从Python执行Maple,并且想要在程序超出最大时间时停止该程序。如果它的Python函数可以通过使用timeout-decorator来完成。但我不确定如何执行命令行调用。这里是伪代码如何在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 

只是为了计时这个程序,一切正常。然而,枫树程序花了很多时间,所以我想定义一个最大时间,检查最大时间是否为t1 <,然后让程序执行其他的否。即改变脚本为这样的:

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') 

目前这是行不通的。有一个更好的方法吗?

+0

有更好的方法来做到这一点。使用'timeout'命令行util已经做了你需要的东西。如果您使用Windows,请尝试查找Windows的类似实用程序。 –

+0

嗨!真的,我相信这是对于Python版本> 3。我使用2.7,这就是现在的渔获。 – jkrish

+0

如果你想使用它的Python - 请参阅下面的Artur的答案 - 这是绝对正确:) –

回答

-1

我认为你可以使用

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

要延迟

0

使用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)