I want to assign the output of a command I run using os.system
to a variable and prevent it from being output to the screen. But, in the below code ,the output is sent to the screen and the value printed for var
is 0, which I guess signifies whether the command ran successfully or not. Is there any way to assign the command output to the variable and also stop it from being displayed on the screen?
var = os.system("cat /etc/services")
print var #Prints 0
I know this has already been answered, but I wanted to share a potentially better looking way to call Popen via the use of
from x import x
and functions:From "Equivalent of Bash Backticks in Python", which I asked a long time ago, what you may want to use is
popen
:From the docs for Python 3.6,
Here's the corresponding code for
subprocess
:For python 3.5+ it is recommended that you use the run function from the subprocess module. This returns a
CompletedProcess
object, from which you can easily obtain the output as well as return code. Since you are only interested in the output, you can write a utility wrapper like this.The commands module is a reasonably high-level way to do this:
status is 0, output is the contents of /etc/services.
Python 2.6 and 3 specifically say to avoid using PIPE for stdout and stderr.
The correct way is
You might also want to look at the
subprocess
module, which was built to replace the whole family of Pythonpopen
-type calls.The advantage it has is that there is a ton of flexibility with how you invoke commands, where the standard in/out/error streams are connected, etc.