Reputation: 831
I have a C(on windows) program which has a main function which returns a value.
#include <stdio.h>
int testData()
{
int testErr = 0;
// ....
return(testErr);
}
int main(void) {
int mainErr = 0;
mainErr = testData();
printf("mainerr = %d", mainErr);
return mainErr;
}
This C code executable myTest.exe is run through python.
self.run_cmd = "myTest.exe "+cmd # pass agruments to the C exe
self.testRun = subprocess.run(self.run_cmd,
stdout=subprocess.PIPE, stdin=None, stderr=subprocess.PIPE,
bufsize=0, universal_newlines=True, timeout=100)
print(">>>>", self.testRun.stdout)
print(">>>>", self.testRun.stderr)
Using "print(">>>>", self.testRun.stdout)" I am not getting the C code's return value in python. In python how to get the return value returned by C main.
Upvotes: 0
Views: 2224
Reputation: 31
The return value obtained from using subprocess will be bytes. After running :
self.testRun = subprocess.run(self.run_cmd, stdout=subprocess.PIPE, stdin=None, stderr=subprocess.PIPE, bufsize=0, universal_newlines=True, timeout=100)
You can capture the output as :
result = self.testRun.stdout.decode('utf-8')
This result is a string and can be used further.
Upvotes: 0
Reputation: 349
In python subprocess
module monitors the return value of the command (i.e. 0 for success and 1 for failure). Since you are returning some value from your C program the program successfully exited with return code 0. What you can do here is you can use exit(1)
in your C program to terminate the program with exit code 1 where you want to return 1.
The exit code of the C program can be monitored using,
subproc = subprocess.run(<command to execute>, stdout=subprocess.PIPE, stderr=subprocess.PIPE,)
if (subproc.returncode == 0):
logger.info('Exited successfully')
Other way is to write your desired output in some files or DB and read that from your python code.
Upvotes: 0
Reputation: 409482
The run
function returns a CompletedProcess
object, which have a returncode
property.
Upvotes: 2