python - Python 函数调用超时

标签 python function timeout

我有这个代码

    r = x.run("prog", ["-4"], ['\tab \t cd\n', ' \t ab cd \n', '\ta\b\b\b\tb\n'])

哪里"prog"是可执行 c 文件的名称,"-4""prog" 使用的命令行参数和'\tab \t cd\n', ' \t ab cd \n', '\ta\b\b\b\tb\n'是文件 "prog" 的输入文本

我的run功能是...

    def run(self, prog, args, input):
    global debug
    result = None
    prog = os.path.join(".",prog)
    command = [prog] + args
    self.createFile(CompileAndExecute.stdinName, input)
    cwd = os.getcwd()
    os.chdir(self.tmpdir)
    stream0 = open(CompileAndExecute.stdinName, "r")
    stream1 = open(CompileAndExecute.stdoutName, "w")
    stream2 = open(CompileAndExecute.stderrName, "w")
    p = None

    try:
        p = subprocess.call(command,
            stdin=stream0, stdout=stream1, stderr=stream2)
    except:
        result = sys.exc_info()
        if p != None:
            p.kill()
    finally:
        stream0.close()
        stream1.close()
        stream2.close()
        os.remove(CompileAndExecute.stdinName)
    os.chdir(cwd)
    return result

我想在我的 run 中添加另一个参数函数,名为 timeout 。 基本上,我想要它,以便如果我的 run函数运行时间超过 5 秒,我会调用 Sys.exit(1)并在那里结束。

我的run的正确调用函数,添加 timeout参数,将是

r = x.run("prog", ["-4"], ['\tab \t cd\n', ' \t ab cd \n', '\ta\b\b\b\tb\n'], 5)

我的完整代码的总体思路(所有内容都不在这里)是编译并执行一个 C 文件并检查其输出是否是应有的结果。

有人建议我查看 Python3 库文档的第 17.5.1 节,以获取有关如何实现超时的信息,但我无法理解如何实现。我尝试了一些类似问题的解决方案,但没有成功。

有什么帮助吗?

编辑: 更多信息请参阅run功能..

run(self, prog,args=[],input=[])

prog 参数是一个字符串,它指定临时目录中的可执行文件的名称。 args 参数包含一个字符串列表,这些字符串将用作 prog 命名的程序的命令行参数。 run 方法执行程序,提供命令行参数。如果程序在运行时从其标准输入读取,则该标准输入将从名为 input 的参数中获取。输入参数是一个字符串列表;每个字符串代表程序要读取的一行文本输入。 当 run 方法返回时,结果要么是 None(显然成功完成),要么是一个字符串(指定程序未执行或未成功完成的原因)。无论函数调用返回什么,都应该检查标准输出流和标准错误输出流。

CompileAndExecuterun 的类名发现于..

class CompileAndExecute:
"""The class provides methods for compiling and testing
a program in a temporary directory."""
stdoutName = ".stdout.txt"
stderrName = ".stderr.txt"
stdinName  = ".stdin.txt"

# constructor, creates temporary directory
def __init__(self, compiler):
    self.compiler = compiler
    self.tmpdir = tempfile.mkdtemp()

更新: 经过一些帮助后,我收到语法错误

    def run(self, prog, args, input):
    global debug
    result = None
    prog = os.path.join(".",prog)
    command = [prog] + args
    self.createFile(CompileAndExecute.stdinName, input)
    cwd = os.getcwd()
    os.chdir(self.tmpdir)
    stream0 = open(CompileAndExecute.stdinName, "r")
    stream1 = open(CompileAndExecute.stdoutName, "w")
    stream2 = open(CompileAndExecute.stderrName, "w")
    p = None

    try:
        p = subprocess.call(command,
        stdin=stream0, stdout=stream1, stderr=stream2, timeout = 5)
        except subprocess.TimeoutExpired:
            sys.exit(1)
        except:
            result = sys.exc_info()
        if p != None:
            p.kill()
     finally:
        stream0.close()
        stream1.close()
        stream2.close()
        os.remove(CompileAndExecute.stdinName)
    os.chdir(cwd)
    return result

对于上述 block 中的代码行,except subprocess.TimeoutExpired:

最佳答案

对于 Python 3+ ,您可以使用 subprocess.calltimeout 参数。 ,传入您想要指定的超时,然后如果在子进程终止之前超时到期,子进程将终止子进程并引发 subprocess.TimeoutExpired 异常,您可以捕获该异常,然后调用 sys.exit(1) 。

所以在你的代码中,你会这样做 -

try:
    p = subprocess.call(command,
        stdin=stream0, stdout=stream1, stderr=stream2, timeout=5)
except subprocess.TimeoutExpired:
    import sys #don't need this here, if you have imported anywhere above.
    sys.exit(1)
except:
    result = sys.exc_info()
    if p != None:
        p.kill()

此外,subprocess.call函数返回返回码,而不是进程本身,因此尝试在内执行p.kill(),除了: 不执行任何操作。

演示 -

import sys
try:
    subprocess.call(['python','a.py'],timeout=1)
except subprocess.TimeoutExpired:
    sys.exit(1)

其中a.py是一个Python脚本,循环100000次。

关于python - Python 函数调用超时,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31665842/

相关文章:

python - Dask 工作人员进入卡住状态并且不会回来

python - 用另一个列表切片列表

c - vector 的长度,初学者

python - 正则表达式自动在函数输入上运行?

php - youtube gdata超时

python - 如何从 cfg 文件中检索键值对

python 3.X : How to insert new row in excel using Xlrd3 library

python - 函数输出为整数(TypeError : must be str, 不是 int)

concurrency - 如何在设置秒数后结束 APScheduler 作业?

android - 屏幕超时会破坏文本到语音应用程序