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

## The Question :

328 people think this question is useful

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


• Don’t use os.system (nor os.popen, per the answer you accepted): use subprocess.Popen, it’s way better!
• @AlexMartelli, one can’t use a complex commands (e.g. piped) in subprocess.Popen(), but with os.system one can
• @vak, of course you can use pipes &c w/subprocess.Popen — just add shell=True!
• @AlexMartelli shell=True is (generally) a very bad idea! You have to be very sure of what you’re executing 🙂

484 people think this answer is useful

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



189 people think this answer is useful

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.

48 people think this answer is useful

The commands module is a reasonably high-level way to do this:

import commands
status, output = commands.getstatusoutput("cat /etc/services")



status is 0, output is the contents of /etc/services.

33 people think this answer is useful

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.

from subprocess import PIPE, run

def out(command):
result = run(command, stdout=PIPE, stderr=PIPE, universal_newlines=True, shell=True)
return result.stdout

my_output = out("echo hello world")
# Or
my_output = out(["echo", "hello world"])



29 people think this answer is useful

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 subprocess import PIPE, Popen

def cmdline(command):
process = Popen(
args=command,
stdout=PIPE,
shell=True
)
return process.communicate()[0]

print cmdline("cat /etc/services")
print cmdline('ls')
print cmdline('rpm -qa | grep "php"')



5 people think this answer is useful

i do it with os.system temp file:

import tempfile,os
ftmp = tempfile.NamedTemporaryFile(suffix='.out', prefix='tmp', delete=False)
fpath = ftmp.name
if os.name=="nt":
fpath = fpath.replace("/","\\") # forwin
ftmp.close()
os.system(cmd + " > " + fpath)
data = ""
with open(fpath, 'r') as file:
file.close()
os.remove(fpath)
return data



2 people think this answer is useful

Python 2.6 and 3 specifically say to avoid using PIPE for stdout and stderr.

The correct way is

import subprocess

# must create a file object to store the output. Here we are getting
# the ssid we are connected to
outfile = open('/tmp/ssid', 'w');
status = subprocess.Popen(["iwgetid"], bufsize=0, stdout=outfile)
outfile.close()

# now operate on the file



1 people think this answer is useful
from os import system, remove
from uuid import uuid4

def bash_(shell_command: str) -> tuple:
"""

:return: ( 1 | 0, stdout)
"""

logfile: str = '/tmp/%s' % uuid4().hex
err: int = system('%s &amp;> %s' % (shell_command, logfile))
>>> (0, '3296\n')
`