gpt4 book ai didi

python - 对于 subprocess.stderr=STDOUT - stdout=PIPE 比 stdout ="a_file_name"更好吗?

转载 作者:太空宇宙 更新时间:2023-11-03 16:52:59 27 4
gpt4 key购买 nike

[已编辑]
用于处理 subprocess.Popen 标准输出的 2 个选项是 stdout="a_file_name"stdout=subprocess.PIPE
stderr 可以通过 stderr=subprocess.STDOUT 与其中任何一个组合。

对于我目前正在做的事情(模糊测试),我生成的 stdout="a_file_name" 代码稍微更短、更清晰。

但是,据我所知,stdout=PIPE 似乎经常受到其他人的青睐,但我不确定其中的所有原因。

如果 Popen([cmd, arg], ...) 中使用的 cmd 是外部可执行文件,它将错误输出写入 stderr stdout=PIPEstdout="a_file_name" 更好吗?

各自的优点和缺点是什么?

  • 在我的特定上下文中(请参阅下面的代码片段),我可以看到使用 stdout=PIPE 而不是 stdout="a_file_name" 的 1 个优点是前者会让我轻松地跳过编写空文件。
  • 如果发生 cmd 崩溃,这 2 个中的 1 个是否更有可能以某种方式获得所有错误输出?

尽管我考虑到了特定的背景,但我也有兴趣了解更一般情况的答案。

为了更好地解释我的上下文,这里是我的 2 个替代代码段:

import subprocess
import sys

assert sys.version_info >= (3, 3)
# timeout added for subprocess's wait() and communicate() in Python 3.3.

with open('sub_proc1.outerr', 'w') as f_outerr1:
sub_proc1 = subprocess.Popen([cmd, args], stdout=f_outerr1,
stderr=subprocess.STDOUT,
universal_newlines=True)
try:
return_code = sub_proc1.wait(timeout=10)
print('*** %s CRASHED with return code: %d.' % (cmd, return_code))
except subprocess.TimeoutExpired:
print('*** %s succeeded.' % cmd)
sub_proc1.kill()

对比:

...
with open('sub_proc2.outerr', 'w') as f_outerr2:
sub_proc2 = subprocess.Popen([cmd, args], stdout=subprocess.PIPE,
stderr=subprocess.STDOUT,
universal_newlines=True)
try:
(sub_proc2_out, sub_proc2_err) = sub_proc2.communicate(timeout=10)
print('*** %s CRASHED with return code: %d.' %
(cmd, sub_proc2.poll()))
assert sub_proc2_err is None
# Since stderr was redirected to STDOUT, this should be None.
f_outerr2.write(str(sub_proc2_out or ""))
# Treat 'None' as an empty string).
except subprocess.TimeoutExpired:
print('*** %s succeeded.' % cmd)
sub_proc2.kill()

原帖:

TITLE: subprocess: Pros and cons of stderr=STDOUT vs. stderr=PIPE?

The 2 principal alternatives for handling error output from 'subprocess.Popen' seem to be 'stderr=STDOUT' (with 'stdout="some_file"') and 'stderr=PIPE'.

For what I want to do (fuzz-testing), my resulting 'stderr=STDOUT' code is a little shorter and cleaner.

However, from what I've read, it seems that 'stderr=PIPE' is preferred, but I'm not sure of all of the reasons why.

If the 'cmd' used is an external executable which writes error output to 'stderr', what are the pros and cons of using 'stderr=STDOUT' versus 'stderr=PIPE'?

...

最佳答案

写入特定文件意味着如果一次运行多次,您的程序将会发生冲突,因为两个进程都想要写入同一个文件。 (搜索临时文件创建问题和安全漏洞)

使用管道意味着不存在文件名唯一性问题。

你关心输出吗?如果没有,则使用 subprocess.DEVNULL ,它会为您丢弃输出。

关于python - 对于 subprocess.stderr=STDOUT - stdout=PIPE 比 stdout ="a_file_name"更好吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35710305/

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