Is there a variant of subprocess.call
that can run the command without printing to standard out, or a way to block out it's standard out messages?
相关问题
- how to define constructor for Python's new Nam
- streaming md5sum of contents of a large remote tar
- How to get the background from multiple images by
- Evil ctypes hack in python
- Correctly parse PDF paragraphs with Python
This is a recipe I use a lot: call
subprocess
and collect the output, and when the command succeeds discard the output, but when it fails print the output.Yes. Redirect its
stdout
to/dev/null
.subprocess.call
also accept stdin/stdout/stderr redirections:Often that kind of chatter is on stderr, so you may want to silence that too. Here's my example:
Note:
subprocess.DEVNULL
is available since Python 3.3. If you are still on Python 2:I use subprocess.check_output in such cases and drop the return value. You might want to add a comment your code stating why you are using check_output in place of check_call. check_output is also nicer when a failure occurs and you are interested in the error output. Example code below. The output is seen only when you uncomment the print line. If the command fails, an exception is thrown.