【问题标题】:How to timeout when executing command line programs in Python?在 Python 中执行命令行程序时如何超时?
【发布时间】:2017-06-13 12:52:17
【问题描述】:

我正在从 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

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

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

【问题讨论】:

  • 有更好的方法。要使用 timeout 命令行工具,它已经可以满足您的需要。如果您使用 Windows,请尝试为 Windows 找到类似的实用程序。
  • 嗨!没错,我相信这是针对 Python 版本 > 3 的。我使用的是 2.7,这就是现在的问题。
  • 如果你想使用 Python - 请参阅下面 Artur 的答案 - 绝对正确 :)

标签: python time


【解决方案1】:

您可以使用subprocess.Popen 生成子进程。确保正确处理 stdout 和 stderr。然后使用Popen.wait(timeout)调用并在TimeoutExpired到达时终止进程。

【讨论】:

    【解决方案2】:

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

    【讨论】:

      【解决方案3】:

      我认为你可以使用

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

      延迟后执行函数

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2010-12-03
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多