简体   繁体   English

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

[英]Python: only print stderr, not stdout, from subprocess.call()?

I'm using Python's subprocess.call ( docs here ) and I have a question about standard output. 我正在使用Python的subprocess.call这里的文档 ),我有一个关于标准输出的问题。

I have the following command: 我有以下命令:

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

It works great, but it prints the output of wget, so I get an absolute ton of wget output like: 它工作得很好,但它打印出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

How can I change the call so it only prints anything if there is an error? 如何更改呼叫,以便在出现错误时仅打印任何内容?

I have tried studying the subprocess docs , but I think I'm too inexperienced to figure it out for myself. 我曾尝试过研究子流程文档 ,但我认为我太缺乏经验,无法自己解决问题。

Actually I think the easiest way would be to use the '-q' option that 'wget' has. 实际上我认为最简单的方法是使用'wget'所具有的'-q'选项。 You can still catch error by looking at the return value. 您仍然可以通过查看返回值来捕获错误。

wget normally reports all output on stderr, so redirecting stdout will not help with getting errors only. wget通常会报告stderr上的所有输出,因此重定向stdout将无助于仅获取错误。

You can either use -nv (non verbose) or -q (quiet) as options to wget, the difference being that -q does not even report errors while -nv reports errors or a single success line to stderr. 您可以使用-nv (非详细)或-q (安静)作为wget的选项,区别在于-q甚至不报告错误,而-nv报告错误或单个成功行到stderr。

The return code is unchanged in both cases, so it can be used to detect any errors if that's the way you prefer. 返回代码在两种情况下都保持不变,因此如果您喜欢这种方式,它可用于检测任何错误。

EDIT: If you really just want to ignore all output from wget, you can redirect stderr and stdout to a null device; 编辑:如果你真的只想忽略wget的所有输出,你可以将stderrstdout重定向到空设备;

import subprocess
import os

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

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

In my Python 3.3.1 install, DEVNULL can be imported from subprocess instead, but I can't find documentation on exactly what version it was added in. The above works in both Python2 and Python3. 在我的Python 3.3.1安装中,DEVNULL可以从子进程中导入,但是我找不到关于它添加的确切版本的文档。上面的内容适用于Python2和Python3。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM