Reputation: 3251
I am trying to create a python installation script for Ubuntu. I am trying to automate it by creating the script instead of having to type in all the download and compilation commands. What I really want it to do is to not print all the output from the commands, and only output the errors, and print the regular output to a file.
I read this stackoverflow guide and this python document, but there is something I just cannot figure out. Whenever I set the stdout argument for call and Popen to None, it still prints out the output to the shell, which according to the python documentation, shouldn't happen.
For example, lets say we are in a directory with a few files, "a", "b", and "c". According to the python documentation, the following command should output just 0.
>>> subprocess.call(["ls", "-a"])
0
But I'm not getting that. Instead, I'm getting the output:
>>> subprocess.call(['ls', '-a'])
. .. a b c
0
I've tried setting the stdout parameter to None, but it is still printing the output, which is not right. Subprocess.Popen has the same exact behavior. How can I get python to not print the output?
For the record, I am running Ubuntu 14.04 64 bit with python 3.4.0.
Edit: I also tried the above from inside a file and executing the file, but I am still getting the incorrect behavior.
Upvotes: 0
Views: 386
Reputation: 414795
None
means inherit parent's standard streams. To redirect stdout to a file and allow stderr to continue to print to the shell (if the parent's stderr prints to the shell):
import subprocess
with open('your_script.log', 'a') as logfile:
subprocess.check_call(['ls', '-a'], stdout=logfile)
Upvotes: 0
Reputation: 5887
You should read the documentation carefully; from subprocess.call
:
The full function signature is the same as that of the Popen constructor [...]
And from subprocess.Popen
:
With the default settings of None, no redirection will occur; the child’s file handles will be inherited from the parent.
So in general, setting stdout
to None
, will work as setting it to subprocess.STDOUT
. If you need to suppress the output set it to subprocess.DEVNULL
, or to store it in output file, just set the opened file object as the parameter.
To catch and process the output, use subprocess.check_output
.
Upvotes: 3