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

Python

Python Problem Overview


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

Python Solutions


Solution 1 - Python

From "https://stackoverflow.com/questions/1410976/equivalent-of-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

Solution 2 - Python

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.

Solution 3 - Python

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.

Solution 4 - Python

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

Solution 5 - Python

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')

Solution 6 - Python

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

Solution 7 - Python

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

Solution 8 - Python

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')```

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionJohnView Question on Stackoverflow
Solution 1 - PythonChris BunchView Answer on Stackoverflow
Solution 2 - PythonWalter MundtView Answer on Stackoverflow
Solution 3 - PythonianmclauryView Answer on Stackoverflow
Solution 4 - PythonchtenbView Answer on Stackoverflow
Solution 5 - PythonVasili SyrakisView Answer on Stackoverflow
Solution 6 - Pythonlexa-bView Answer on Stackoverflow
Solution 7 - PythonKearney TaaffeView Answer on Stackoverflow
Solution 8 - Pythonlestat_kimView Answer on Stackoverflow