gpt4 book ai didi

python - Python 函数调用超时

转载 作者:太空宇宙 更新时间:2023-11-03 17:32:41 25 4
gpt4 key购买 nike

我有这个代码

    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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com