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

The Question Comments :
  • 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 🙂

The Answer 1

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

The Answer 2

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.

The Answer 3

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.

The Answer 4

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"])

The Answer 5

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(
    return process.communicate()[0]

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

The Answer 6

5 people think this answer is useful

i do it with os.system temp file:

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

The Answer 7

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)

# now operate on the file

The Answer 8

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

def bash_(shell_command: str) -> tuple:

    :param shell_command: your shell command
    :return: ( 1 | 0, stdout)

    logfile: str = '/tmp/%s' % uuid4().hex
    err: int = system('%s &> %s' % (shell_command, logfile))
    out: str = open(logfile, 'r').read()
    return err, out

# Example: 
print(bash_('cat /usr/bin/vi | wc -l'))
>>> (0, '3296\n')```


Add a Comment