How to use shell return value like $? In python?

Nick Dokos nicholas.dokos at hp.com
Sun Oct 23 23:23:12 EDT 2011


David Riley <fraveydank at gmail.com> wrote:

> On Oct 23, 2011, at 10:44 PM, aaabbb16 at hotmail.com wrote:
> 
> > exp:
> > os.system('ls -al')
> > #I like to catch return value after this command. 0 or 1,2,3....
> > does python support to get "$?"?
> > then I can use something like:
> > If $?==0:
> >     ........
> > ................
> 
> From the manual (http://docs.python.org/library/os.html#os.system):
> 
> "On Unix, the return value is the exit status of the process encoded in the format specified for wait(). Note that POSIX does not specify the meaning of the return value of the C system() function, so the return value of the Python function is system-dependent."
> 
> From the linked wait() documentation, the data returned is in a 16-bit integer, with the high byte indicating the exit status (the low byte is the signal that killed the process).  So:
> 
> 
> 
> 
> status = os.system("foo")
> 
> retval, sig = ((status >> 8) & 0xFF), (status & 0xFF)
> 

... or

retval, sig = os.WEXITSTATUS(status), os.WTERMSIG(status)

for some insulation from low-level details.

Nick
> 
> 
> 
> In the above example, your return status will end up in "retval".
> 
> Of course, you probably ought to be using subprocess to run your subprocesses anyway; it's a lot more powerful and a lot harder to enable things like shell injection attacks.  See: http://docs.python.org/library/subprocess.html#subprocess-replacements (which, of course, shows a direct replacement for os.system which is just as vulnerable to shell injection)
> 
> 
> - Dave
> 
> -- 
> http://mail.python.org/mailman/listinfo/python-list



More information about the Python-list mailing list