RKum
RKum

Reputation: 831

How to get return value by C program in python

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

Answers (3)

Parv Sachdeva
Parv Sachdeva

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

Soumyajit
Soumyajit

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

Some programmer dude
Some programmer dude

Reputation: 409482

The run function returns a CompletedProcess object, which have a returncode property.

Upvotes: 2

Related Questions