How to save os.system () output in a variable or list in python

I am trying to get the output of a command by running ssh on a remote server using the following command.

os.system('ssh user@host " ksh .profile; cd dir; find . -type f |wc -l"') 

The output of this command: 14549 0

why is there zero in the output? Is there any way to store the output in a variable or list? I tried to assign the output to the variable and the list, but I only get 0 in the variable. I am using python 2.7.3.

+6
source share
4 answers

There are many good SO links on this. try running the shell command from Python and grabbing the output or Assign the output of the os.system to a variable and not showing it on the screen to begin with. In short

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

The shell character = True should be used with care:

From the docs: Warning

Invoking a system shell with shell = True can be a security risk in combination with untrusted input. See the Frequently Used Arguments section for more details.

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

+8
source

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

I rewrote it a bit to make it easier to work with commands that may cause errors (for example, calling "git status" in a non-git directory will trigger a 128 return code and CalledProcessError)

Here is 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 
+1
source

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

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

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

 import os out = os.popen('date').read() print out Tue Oct 3 10:48:10 PDT 2017 
0
source

Source: https://habr.com/ru/post/955554/


All Articles