1

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?

Alexander Kalian
  • 1,059
  • 2
  • 9
  • 17
  • 1
    possible duplicate of [Assign output of os.system to a variable and prevent it from being displayed on the screen](http://stackoverflow.com/questions/3503879/assign-output-of-os-system-to-a-variable-and-prevent-it-from-being-displayed-on) – Emilien Jul 18 '14 at 13:19
  • You could be right. I'm checking out the solution there to see if my question is useless. – Alexander Kalian Jul 18 '14 at 13:23
  • 1
    @Emilien No, that is talking about a related, but different, task (capturing the *output* of a program, not its exit code). – zwol Jul 18 '14 at 13:25

3 Answers3

3

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 the subprocess Module section in the subprocess 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
ford
  • 10,687
  • 3
  • 47
  • 54
1

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)
falsetru
  • 357,413
  • 63
  • 732
  • 636
1

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.

zwol
  • 135,547
  • 38
  • 252
  • 361