Reputation: 1159
I'm using the the python os.system to print a value received from a C file.
My C file says...
#include <stdio.h>
main()
{
printf("hello world\n");
return 7;
}
Then I have a python file which does the following...
import os
x = os.system("./a.out")
print x
When I run the python program on a linux command line, I get "hello world" successfully printed, but the variable x is printed as 1792.
I want x to be printed as 7, not 1792. Why is x being printed as 1792 and how do I fix it?
Upvotes: 1
Views: 334
Reputation: 369444
According to os.system
documentation:
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.
Use os.WEXITSTATUS
to get the return code:
import os
x = os.system("./a.out")
print os.WEXITSTATUS(x)
Upvotes: 1
Reputation: 11876
The other answers about os.WEXITSTATUS
are correct, but the recommended way to do this is with subprocess
. The documentation for os.system
includes the following paragraph:
The
subprocess
module provides more powerful facilities for spawning new processes and retrieving their results; using that module is preferable to using this function. See the Replacing Older Functions with thesubprocess
Module section in thesubprocess
documentation for some helpful recipes.
Since you are interested in the return code, you can use subprocess.call
:
import subprocess
x = subprocess.call(['./a.out'])
print x
Upvotes: 3
Reputation: 140866
The value returned from os.system
is a wait status, which contains an encoding of the value returned by the program, plus other information. You decode it with os.WIFEXITED
, os.WEXITSTATUS
, and their relatives.
>>> import os
>>> x = os.system("exit 7")
>>> x
1792
>>> os.WIFEXITED(x)
True
>>> os.WEXITSTATUS(x)
7
Two additional details you need to know are: If the value returned from main
(or passed to exit
) is negative or greater than 255, it will be truncated. If os.WIFEXITED(x)
is false, os.WEXITSTATUS(x)
is garbage.
Upvotes: 1