Python:只从subprocess.call()打印stderr而不是stdout?

时间:2013-06-28 07:56:01

标签: python subprocess stderr

我正在使用Python的subprocess.calldocs here),我对标准输出有疑问。

我有以下命令:

subprocess.call("wget http://google.com", shell=True)

它工作得很好,但它打印出wget的输出,所以我得到了绝对吨的wget输出,如:

--2013-06-28 08:54:47--  http://google.com/
Resolving google.com... 173.194.41.100, 173.194.41.98, 173.194.41.97, ...
Connecting to google.com|173.194.41.100|:80... connected.
HTTP request sent, awaiting response... 301 Moved Permanently
.... etc

如何更改通话,以便在出现错误时只打印任何内容?

我曾尝试过研究the subprocess docs,但我觉得我太缺乏经验,无法自己解决这个问题。

2 个答案:

答案 0 :(得分:1)

实际上我认为最简单的方法是使用'wget'所具有的'-q'选项。您仍然可以通过查看返回值来捕获错误。

答案 1 :(得分:1)

wget通常会在stderr上报告所有输出,因此重定向stdout无助于仅获取错误。

您可以使用-nv(非详细)或-q(安静)作为wget的选项,不同之处在于-q甚至不报告错误-nv向stderr报告错误或单个成功行。

在这两种情况下,返回代码都没有改变,因此如果您愿意,可以使用它来检测任何错误。

编辑:如果你真的只想忽略wget的所有输出,你可以将stderrstdout重定向到空设备;

import subprocess
import os

DEVNULL = open(os.devnull, 'wb')

subprocess.call("wget http://google.com/", stdout=DEVNULL, stderr=DEVNULL, shell=True)

在我的Python 3.3.1安装中,DEVNULL可以从子进程中导入,但是我找不到关于它添加到哪个版本的文档。上面的内容适用于Python2和Python3。