Linux command-line call not returning what it should from os.system?

311,537

Solution 1

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

or

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

ON SO : Popen and python

Solution 2

If you're only interested in the output from the process, it's easiest to use subprocess' check_output function:


output = subprocess.check_output(["command", "arg1", "arg2"]);

Then output holds the program output to stdout. Check the link above for more info.

Solution 3

The simplest way is like this:

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

This will be returned as a list

Solution 4

Your code returns 0 if the execution of the commands passed is successful and non zero if it fails. The following program works on python2.7, haven checked 3 and versions above. Try this code.

>>> import commands
>>> ret = commands.getoutput("ps -p 2993 -o time --no-headers")
>>> print ret

Solution 5

Yes it's counter-intuitive and does not seem very pythonic, but it actually just mimics the unix API design, where these calld are C POSIX functions. Check man 3 popen && man 3 system

Somewhat more convenient snippet to replace os.system that I use:

from subprocess import (PIPE, Popen)


def invoke(command):
    '''
    Invoke command as a new system process and return its output.
    '''
    return Popen(command, stdout=PIPE, shell=True).stdout.read()


result = invoke('echo Hi, bash!')
# Result contains standard output (as you expected it in the first place).
Share:
311,537
Rick
Author by

Rick

Web programmer with an interest in web task automation, building websites, etc, I prefer to do everything in Python now as I have moved to it from using a variety of other languages in the past. I also like to do front-end AJAX / javascript work but am moving to do this through Python as well, with the Pyjamas framework.

Updated on July 21, 2020

Comments

  • Rick
    Rick almost 4 years

    I need to make some command line calls to linux and get the return from this, however doing it as below is just returning 0 when it should return a time value, like 00:08:19, I am testing the exact same call in regular command line and it returns the time value 00:08:19 so I am confused as to what I am doing wrong as I thought this was how to do it in python.

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