回答此问题可获得 20 贡献值,回答如果被采纳可获得 50 分。
<p>我想执行一个进程,将执行时间限制为以秒为单位的超时,并获取该进程产生的输出。我想在windows,linux和freebsd上做这个。</p>
<p>我试着用三种不同的方式来实现这一点:</p>
<ol>
<li><p>没有超时和输出捕获的subprocess.PIPE。</p>
<p>行为:按预期操作但不支持超时,我需要超时。。。</p></li>
<li><p>cmd_to-带超时和用于输出捕获的subprocess.PIPE。</p>
<p>行为:当输出>;=2^16字节时阻止子进程执行。</p></li>
<li><p>cmd_totf-带超时和tempfile.NamedTemporaryfile用于输出捕获。</p>
<p>行为:按预期操作,但使用磁盘上的临时文件。</p></li>
</ol>
<p>下面提供这些以供进一步检查。</p>
<p>从下面的输出中可以看出,使用subprocessing.PIPE时,超时代码会阻止子进程的执行,并且子进程的输出为2^16字节。</p>
<p>子流程文档指出,调用process.wait()和使用subprocessing.PIPE时会出现这种情况,但是在使用process.poll()时不会发出警告,所以这里出了什么问题?</p>
<p>我在cmd_totf中有一个使用tempfile模块的解决方案,但是折衷的办法是它将输出写到磁盘,这是我真正想避免的。</p>
<p>所以我的问题是:</p>
<ul>
<li>我在命令里做错了什么?</li>
<li>有没有办法做我想做的事而不使用tempfiles/将输出保存在内存中。</li>
</ul>
<p>生成一组输出(“exp_gen.py”)的脚本:</p>
<pre><code>#!/usr/bin/env python
import sys
output = "b"*int(sys.argv[1])
print output
</code></pre>
<p>子流程周围的包装器有三种不同的实现方式(cmd、cmd、cmd)</p>
<pre><code>#!/usr/bin/env python
import subprocess, time, tempfile
bufsize = -1
def cmd(cmdline, timeout=60):
"""
Execute cmdline.
Uses subprocessing and subprocess.PIPE.
"""
p = subprocess.Popen(
cmdline,
bufsize = bufsize,
shell = False,
stdin = subprocess.PIPE,
stdout = subprocess.PIPE,
stderr = subprocess.PIPE
)
out, err = p.communicate()
returncode = p.returncode
return (returncode, err, out)
def cmd_to(cmdline, timeout=60):
"""
Execute cmdline, limit execution time to 'timeout' seconds.
Uses subprocessing and subprocess.PIPE.
"""
p = subprocess.Popen(
cmdline,
bufsize = bufsize,
shell = False,
stdin = subprocess.PIPE,
stdout = subprocess.PIPE,
stderr = subprocess.PIPE
)
t_begin = time.time() # Monitor execution time
seconds_passed = 0
while p.poll() is None and seconds_passed < timeout:
seconds_passed = time.time() - t_begin
time.sleep(0.1)
#if seconds_passed > timeout:
#
# try:
# p.stdout.close() # If they are not closed the fds will hang around until
# p.stderr.close() # os.fdlimit is exceeded and cause a nasty exception
# p.terminate() # Important to close the fds prior to terminating the process!
# # NOTE: Are there any other "non-freed" resources?
# except:
# pass
#
# raise TimeoutInterrupt
out, err = p.communicate()
returncode = p.returncode
return (returncode, err, out)
def cmd_totf(cmdline, timeout=60):
"""
Execute cmdline, limit execution time to 'timeout' seconds.
Uses subprocessing and tempfile instead of subprocessing.PIPE.
"""
output = tempfile.NamedTemporaryFile(delete=False)
error = tempfile.NamedTemporaryFile(delete=False)
p = subprocess.Popen(
cmdline,
bufsize = 0,
shell = False,
stdin = None,
stdout = output,
stderr = error
)
t_begin = time.time() # Monitor execution time
seconds_passed = 0
while p.poll() is None and seconds_passed < timeout:
seconds_passed = time.time() - t_begin
time.sleep(0.1)
#if seconds_passed > timeout:
#
# try:
# p.stdout.close() # If they are not closed the fds will hang around until
# p.stderr.close() # os.fdlimit is exceeded and cause a nasty exception
# p.terminate() # Important to close the fds prior to terminating the process!
# # NOTE: Are there any other "non-freed" resources?
# except:
# pass
#
# raise TimeoutInterrupt
p.wait()
returncode = p.returncode
fd = open(output.name)
out = fd.read()
fd.close()
fd = open(error.name)
err = fd.read()
fd.close()
error.close()
output.close()
return (returncode, err, out)
if __name__ == "__main__":
implementations = [cmd, cmd_to, cmd_totf]
bytes = ['65535', '65536', str(1024*1024)]
timeouts = [5]
for timeout in timeouts:
for size in bytes:
for i in implementations:
t_begin = time.time()
seconds_passed = 0
rc, err, output = i(['exp_gen.py', size], timeout)
seconds_passed = time.time() - t_begin
filler = ' '*(8-len(i.func_name))
print "[%s%s: timeout=%d, iosize=%s, seconds=%f]" % (repr(i.func_name), filler, timeout, size, seconds_passed)
</code></pre>
<p>执行输出:</p>
<pre><code>['cmd' : timeout=5, iosize=65535, seconds=0.016447]
['cmd_to' : timeout=5, iosize=65535, seconds=0.103022]
['cmd_totf': timeout=5, iosize=65535, seconds=0.107176]
['cmd' : timeout=5, iosize=65536, seconds=0.028105]
['cmd_to' : timeout=5, iosize=65536, seconds=5.116658]
['cmd_totf': timeout=5, iosize=65536, seconds=0.104905]
['cmd' : timeout=5, iosize=1048576, seconds=0.025964]
['cmd_to' : timeout=5, iosize=1048576, seconds=5.128062]
['cmd_totf': timeout=5, iosize=1048576, seconds=0.103183]
</code></pre>