Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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 
like image 301
Rick Avatar asked Sep 24 '10 22:09

Rick


People also ask

What happens when you run a command in Linux?

Running the CommandThe shell makes a copy of itself, a process called forking. This copy of the shell replaces itself with the command, with all of the arguments that were processed earlier. This is known as an "exec," and the combined process is known as "fork-and-exec."

What does & do at the end of command line?

If a command is terminated by the control operator &, the shell executes the command in the background in a subshell. The shell does not wait for the command to finish, and the return status is 0.


1 Answers

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

like image 191
pyfunc Avatar answered Sep 23 '22 12:09

pyfunc