忽略 subprocess.Popen 的输出

2022-01-18 00:00:00 python subprocess

问题描述

我正在从我的 Python 脚本调用一个 java 程序,它输出了很多我不想要的无用信息.我已经尝试将 stdout=None 添加到 Popen 函数中:

I am calling a java program from my Python script, and it is outputting a lot of useless information I don't want. I have tried addind stdout=None to the Popen function:

subprocess.Popen(['java', '-jar', 'foo.jar'], stdout=None)

但它也是一样的.有什么想法吗?

But it does the same. Any idea?


解决方案

来自 3.3 文档:

stdin、stdout 和 stderr 分别指定执行程序的标准输入、标准输出和标准错误文件句柄.有效值为 PIPE、DEVNULL、现有文件描述符(正整数)、现有文件对象和无.

stdin, stdout and stderr specify the executed program’s standard input, standard output and standard error file handles, respectively. Valid values are PIPE, DEVNULL, an existing file descriptor (a positive integer), an existing file object, and None.

所以:

subprocess.check_call(['java', '-jar', 'foo.jar'], stdout=subprocess.DEVNULL)

这仅存在于 3.3 及更高版本中.但是文档说:

This only exists in 3.3 and later. But the documentation says:

DEVNULL 表示将使用特殊文件 os.devnull.

DEVNULL indicates that the special file os.devnull will be used.

os.devnull 可以追溯到 2.4(在 subprocess 存在之前).因此,您可以手动执行相同的操作:

And os.devnull exists way back to 2.4 (before subprocess existed). So, you can do the same thing manually:

with open(os.devnull, 'w') as devnull:
    subprocess.check_call(['java', '-jar', 'foo.jar'], stdout=devnull)

请注意,如果您正在做一些不适合一行的更复杂的事情,您需要在 Popen 的整个生命周期内保持 devnull 处于打开状态对象,而不仅仅是它的构造.(也就是说,将整个内容放在 with 语句中.)

Note that if you're doing something more complicated that doesn't fit into a single line, you need to keep devnull open for the entire life of the Popen object, not just its construction. (That is, put the whole thing inside the with statement.)

重定向到 /dev/null (POSIX) 或 NUL: (Windows) 的优点是您不会创建不必要的管道,更重要的是,不能遇到子进程在写入该管道时阻塞的极端情况.

The advantage of redirecting to /dev/null (POSIX) or NUL: (Windows) is that you don't create an unnecessary pipe, and, more importantly, can't run into edge cases where the subprocess blocks on writing to that pipe.

缺点是,理论上,subprocess 可能在某些os.devnull 不具备的平台上工作.如果您只关心 POSIX 和 Windows、PyPy 和 Jython(大多数人)上的 CPython,那么这永远不会成为问题.对于其他情况,请在分发代码之前进行测试.

The disadvantage is that, in theory, subprocess may work on some platforms that os.devnull does not. If you only care about CPython on POSIX and Windows, PyPy, and Jython (which is most of you), this will never be a problem. For other cases, test before distributing your code.

相关文章