There are several ways of calling C++ executable programs. For example, we can use
def run_exe_return_code(run_cmd):
process=subprocess.Popen(run_cmd,stdout=subprocess.PIPE,shell=True)
(output,err)=process.communicate()
exit_code = process.wait()
print output
print err
print exit_code
return exit_code
to process a C++ executable program: run_exe_return_code('abc')
while abc
is created by the following C++ codes:
int main()
{
return 1;
}
In the above codes, the return value of the program is 1, and if we run this Python script in Linux we can always see the return value by the Python script is 1. However, in Android environment it seems that the return exit code in the above python script is 0, which means successful. Is there a solution where the Python script can know the return value of main function in Android enviroment? Thanks.
By the way, in android environment, I use adb shell abc
instead of abc
in order to run the program.
Best How To :
For your android problem you can use fb-adb
which "propagates program exit status instead of always exiting with status 0" (preferred), or use this workaround (hackish... not recommended for production use):
def run_exe_return_code(run_cmd):
process=subprocess.Popen(run_cmd + '; echo $?',stdout=subprocess.PIPE,shell=True)
(output,err)=process.communicate()
exit_code = process.wait()
print output
print err
print exit_code
return exit_code
Note that the last process's code is echo
-ed so get it from the output, not from the exit_code of adb
.
$?
returns the last exit code. So printing it allows you to access it from python.
As to your original question:
I can not reproduce this. Here is a simple example:
Content of .c
file:
[email protected]:~/pyh$ cat c.c
int main() {
return 1;
}
Compile (to a.out
by default...):
[email protected]:~/pyh$ gcc c.c
Content of .py
file:
[email protected]:~/pyh$ cat tstc.py
#!/usr/bin/env python
import subprocess
def run_exe_return_code(run_cmd):
process=subprocess.Popen(run_cmd,stdout=subprocess.PIPE)
(output,err)=process.communicate()
exit_code = process.wait()
print output
print err
print exit_code
run_exe_return_code('./a.out')
Test:
[email protected]:~/pyh$ ./tstc.py
None
1
exit_code
is 1
as expected.
Notice that the return value is always an integer. You may want the output which you can get by using subprocess.check_output
:
Run command with arguments and return its output as a byte string.
Example:
>>> subprocess.check_output(["echo", "Hello World!"])
'Hello World!\n'
Note: If the return value is 1
, which signals an error, a CalledProcessError
exception will be raised (which is usually a good thing since you can respond to it).