Assign output of os.system to a variable and prevent it from being displayed on the screen


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
10/17/2012 8:25:26 PM

Accepted Answer

From "Equivalent of Bash Backticks in Python", which I asked a long time ago, what you may want to use is popen:

os.popen('cat /etc/services').read()

From the docs for Python 3.6,

This is implemented using subprocess.Popen; see that class’s documentation for more powerful ways to manage and communicate with subprocesses.

Here's the corresponding code for subprocess:

import subprocess

proc = subprocess.Popen(["cat", "/etc/services"], stdout=subprocess.PIPE, shell=True)
(out, err) = proc.communicate()
print "program output:", out
3/5/2018 6:03:14 PM

You might also want to look at the subprocess module, which was built to replace the whole family of Python popen-type calls.

import subprocess
output = subprocess.check_output("cat /etc/services", shell=True)

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.

Licensed under: CC-BY-SA with attribution
Not affiliated with: Stack Overflow