Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to store os.system() output in a variable or a list in python [duplicate]

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 this command is 14549 0

why is there a zero in the output ? is there any way of storing the output in variable or list ? I have tried assigning output to a variable and a list too but i am getting only 0 in the variable. I am using python 2.7.3.

like image 766
Jitu Avatar asked Oct 09 '13 09:10

Jitu


People also ask

How do you store OS system output in a variable in Python?

Python subprocess.Using subprocess. check_output() function we can store the output in a variable.

How do you assign an OS system to a variable without displaying it on screen in Python?

check_output() to assign an os. system output to a variable without displaying it on screen. Use syntax subprocess. check_output(arguments, shell = True) with arguments as a string contain command line arguments to return the output of the command line arguments without printing it.

What does OS system return in Python?

os. system() is the state code that is returned after the execution result is executed in the Shell, with 0 indicating a successful execution. os. popen() is the direct return of the execution result, which returns a memory address and parses the data in the memory address with read().


3 Answers

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

like image 54
Paul Avatar answered Oct 27 '22 00:10

Paul


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

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

print out
Tue Oct  3 10:48:10 PDT 2017
like image 33
stingray Avatar answered Oct 27 '22 01:10

stingray


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

class MyProcessHandler( object ):
    # *********** constructor
    def __init__( self ):
        # return code saving
        self.retcode = 0

    # ************ modified copy of subprocess.check_output()

    def check_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 output
        if 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
like image 26
Simon Avatar answered Oct 27 '22 00:10

Simon