Rick Rick - 11 months ago 76
Linux Question

Python, os.system for command-line call (linux) not returning what it should?

I need to make some command line calls to linux and get the return from this, however doing it as below is just returning

when it should return a time value, like
, I am testing the exact same call in regular command line and it returns the time value
so I am confused as to what I am doing wrong as I thought this was how to do it in python. Any advice is appreciated.

import os
retvalue = os.system("ps -p 2993 -o time --no-headers")
print retvalue


What gets returned is the return value of executing this command. What you see in while executing it directly is the output of the command in stdout. That 0 is returned means, there was no error in execution.

Use popen etc for capturing the output .

Some thing along this line:

import subprocess as sub
p = sub.Popen(['your command', 'arg1', 'arg2', ...],stdout=sub.PIPE,stderr=sub.PIPE)
output, errors = p.communicate()
print output


import os
p = os.popen('command',"r")
while 1:
    line = p.readline()
    if not line: break
    print line

ON SO : Popen and python