Search code examples
pythonc++subprocessreturn-valuecout

How to get return value of c++ int main() output using subprocess.check_output() in python script


I am using a C++ script as follows:

int main(){
 int x =7;
 std::cout<<"print num:"<<x<<std::endl;
 if(x>0){
  std::cout<<" good"<<std::endl;
  return 5;
 }
 return 0;
}

For this in my python file I am calling the subprocess as follows:

result0_1 = subprocess.check_output(MYCPP_fILE_PATH,shell =True)
print(result0_1.decode("utf-8"))

It prints out "print num:" and "good" but dosn't provide me the return value "5".

How can I get the return value but not the std::cout from the cpp file?


Solution

  • From Python 3 docs

    And very similar Python 2 docs

    If the return code was non-zero it raises a CalledProcessError. The CalledProcessError object will have the return code in the returncode attribute and any output in the output attribute.