Need help with os.system in linux

Thomas Bellman bellman at lysator.liu.se
Sat Jan 17 02:19:45 EST 2009


akshay bhat <akshayubhat at gmail.com> writes:

> i am calling a program using os.system in python on Linux.
> However in i found that program being executed and soon returned 256.
> but when i ran it using terminal i got proper results.

Under Linux (but unfortunately not generally under Unix), you can
interpret return code from os.system() using os.WIFSIGNALED() or
os.WIFEXITED(), and os.WEXITSTATUS() or os.WTERMSIG().  Something
like this:

    status = os.system(commandline)
    if os.WIFSIGNALED(status):
	print "Command was killed by signal", os.WTERMSIG(status)
    else:
	print "Command exited with return status", os.WEXITSTATUS(status)

(os.WIFSIGNALED() and os.WIFEXITED() are each others inverses,
for this use case.  In the above code, I could have used 'not
os.WIFEXITED(status)' instead of 'os.WIFSIGNALED(status)' without
changing its meaning.)

If you do that for your program, you will see that the program
you call are exiting with return status 1 (that's what a return
value of 256 from os.system() happens to mean), i.e it is calling
exit() with 1 as argument.

*Why* the program you are calling does that, is impossible to
tell from the information you have given us.  You haven't even
told us what command line you are passing to os.system(), so if
you need more help, you must tell us more.


May I also suggest that you use the subprocess module instead of
os.system().  The subprocess module is a newer and better interface
for running external commands.  For example, you can avoid having
to deal with quoting shell metacharacters, and interpreting the
return values are easier.


-- 
Thomas Bellman,   Lysator Computer Club,   Linköping University,  Sweden
"Life IS pain, highness.  Anyone who tells   !  bellman @ lysator.liu.se
 differently is selling something."          !  Make Love -- Nicht Wahr!



More information about the Python-list mailing list