Skip to content Skip to sidebar Skip to footer

How To Store Os.system() Output In A Variable Or A List In Python

I am trying to get the output of a command by doing ssh on a remote server using below command. os.system('ssh user@host ' ksh .profile; cd dir; find . -type f |wc -l'') Output of

Solution 1:

There are many good SO links on this one. try Running shell command from Python and capturing the output or Assign output of os.system to a variable and prevent it from being displayed on the screen for starters. In short

import subprocess
direct_output = subprocess.check_output('ls', shell=True) #could be anything here.

The shell=True flag should be used with caution:

From the docs: Warning

Invoking the system shell with shell=True can be a security hazard if combined with untrusted input. See the warning under Frequently Used Arguments for details.

See for much more info: http://docs.python.org/2/library/subprocess.html

Solution 2:

you can use os.popen().read()

import os
out = os.popen('date').read()

print out
Tue Oct  310:48:10 PDT 2017

Solution 3:

To add to Paul's answer (using subprocess.check_output):

I slightly rewrote it to work easier with commands that can throw errors (e.g. calling "git status" in a non-git directory will throw return code 128 and a CalledProcessError)

Here's my working Python 2.7 example:

import subprocess

classMyProcessHandler( object ):
    # *********** constructordef__init__( self ):
        # return code saving
        self.retcode = 0# ************ modified copy of subprocess.check_output()defcheck_output2( self, *popenargs, **kwargs ):
        # open process and get returns, remember return code
        pipe = subprocess.PIPE
        process = subprocess.Popen( stdout = pipe, stderr = pipe, *popenargs, **kwargs )
        output, unused_err = process.communicate( )
        retcode = process.poll( )
        self.retcode = retcode

        # return standard output or error outputif retcode == 0:
            return output
        else:
            return unused_err

# call it like this
my_call = "git status"
mph = MyProcessHandler( )
out = mph.check_output2( my_call )
print"process returned code", mph.retcode
print"output:"print out

Solution 4:

If you are calling os.system() in an interactive shell, os.system() prints the standard output of the command ('14549', the wc -l output), and then the interpreter prints the result of the function call itself (0, a possibly unreliable exit code from the command). An example with a simpler command:

Python 3.3.2 (v3.3.2:d047928ae3f6, May 162013, 00:06:53) [MSC v.160064 bit (AMD64)] on win32
Type"help", "copyright", "credits"or"license"for more information.
>>> import os
>>> os.system("echo X")
X
0
>>>

Post a Comment for "How To Store Os.system() Output In A Variable Or A List In Python"