442

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
8
  • 8
    Don't use os.system (nor os.popen, per the answer you accepted): use subprocess.Popen, it's way better! Commented Aug 17, 2010 at 15:28
  • 2
    @AlexMartelli, one can't use a complex commands (e.g. piped) in subprocess.Popen(), but with os.system one can Commented May 25, 2015 at 11:03
  • 2
    @vak, of course you can use pipes &c w/subprocess.Popen -- just add shell=True! Commented May 26, 2015 at 23:06
  • 4
    @AlexMartelli it's not useful to say that something is "way better" without saying why. Commented Mar 1, 2022 at 16:25
  • 1
    @AlexMartelli this is Stack Overflow, where the goal is to provide that type of information to people asking questions rather than telling them to rtm. Even now, it is not clear what fine-grained control is more useful for OP's case. Commented Mar 3, 2022 at 14:25

8 Answers 8

665

From this question 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)
Sign up to request clarification or add additional context in comments.

14 Comments

Note that Walter's subprocess.check_output solution is closer to the Pythonic one-liner it seems you're looking for, as long as you don't care about stderr.
@ChrisBunch Why is suprocess a better solution than os.popen?
You should (almost) never use shell=True. See docs.python.org/3/library/…
I keep coming across this and every time I wonder - why is it better to have three lines of complicated code rather than one line of obvious code?
Not only should you (almost) never use shell=True, but it's also incorrect in this case. shell=True makes the shell the child process rather than cat, so out and err are the stdout/stderr of the shell process rather than of the cat process
|
244

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.

7 Comments

note, check_output was added with python 2.7 docs.python.org/2.7/library/…
Add stderr=subprocess.STDOUT to capture standard errors as well
i used this method with systeminfo command. Output was something nasty like this b'\r\nHost Name: DIMUTH-LAPTOP\r\nOS Name: Microsoft Windows 10 Pro\r\nOS Version: 10.0.10240 N/A Build 10240\r\nOS Manufacturer: Microsoft Corporation
how can i print in line by line . because above output is a mess
@ghost21blade, you might want to look into this: output.decode("utf-8").split("\n") or whatever you´d like to do with it. You must convert it into a string first!
|
49

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.

3 Comments

Quoting from the documentation of the commands module: "Deprecated since version 2.6: The commands module has been removed in Python 3. Use the subprocess module instead.".
sure it's outdated but sometimes you just want to get something done quickly and easily in a few lines of code.
@advocate check out the check_output command of subprocess. It's quick, easy, and won't depreciate soon!
46

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

2 Comments

Dont forget "capture_output=True" option for run()
Using: result = run(command, stdout=PIPE, stderr=PIPE, universal_newlines=True, shell=True, capture_output=True) with capture_output injected returns: ValueError: stdout and stderr arguments may not be used with capture_output.
36

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"')
print cmdline('nslookup google.com')

2 Comments

3 years later, this is what worked for me. I threw this in a separate file called cmd.py, and then in my main file I wrote from cmd import cmdline and used it as needed.
I was getting the same issue with os.system returning 0, but I tried this method and it works great! And as a bonus it looks nice and tidy :) Thanks!
7

I do it with os.system temp file:

import tempfile, os

def readcmd(cmd):
    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:
        data = file.read()
        file.close()
    os.remove(fpath)
    return data

Comments

3

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

Comments

-1
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()
    remove(logfile)
    return err, out

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

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.