Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

in python, get the output of system command as a string [duplicate]

In python I can run some system command using os or subprocess. The problem is that I can't get the output as a string. For example:

>>> tmp = os.system("ls") file1 file2 >>> tmp 0 

I have an older version of subprocess that doesn't have the function check_out, and I would prefer a solution that doesn't require to update that module since my code will run on a server I don't have full admin rights.

This problem seems trivial, yet I couldn't find a trivial solution

like image 533
S4M Avatar asked Oct 08 '13 08:10

S4M


People also ask

What command is used to output text from both the python?

print() is the command you are looking for. The print() function, formally print statement in Python 2.0, can be used to output text from both the python shell and within a python module.

How do I capture the output of a subprocess run?

To capture the output of the subprocess. run method, use an additional argument named “capture_output=True”. You can individually access stdout and stderr values by using “output. stdout” and “output.


1 Answers

Use os.popen():

tmp = os.popen("ls").read() 

The newer way (> python 2.6) to do this is to use subprocess:

proc = subprocess.Popen('ls', stdout=subprocess.PIPE) tmp = proc.stdout.read() 
like image 104
Hari Menon Avatar answered Sep 21 '22 17:09

Hari Menon