Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C, C++ Interface with Python

Tags:

c++

python

c

bash

I have c++ code that has grown exponential. I have a number of variables (mostly Boolean) that need to be changed for each time I run my code (different running conditions). I have done this using the argument command line inputs for the main( int argc, char* argv[]) function in the past.

Since this method has become cumbersome (I have 18 different running conditions, hence 18 different argument :-( ), I would like to move to interfacing with python (if need be Bash ). Ideally I would like to code a python script, where I set the values of data members and then run the code.

Does anyone have a any pointer/information that could help me out? Better still a simple coded example or URL I could look up.

Edit From Original Question:

Sorry I don't think I was clear with my question. I don't want to use the main( int argc, char* argv[]) feature in c++. Instead of setting the variables on the command line. Can I use python to declare and initialize the data members in my c++ code?

Thanks again mike

like image 770
MWright Avatar asked May 11 '11 07:05

MWright


1 Answers

Use subprocess to execute your program from python.

import subprocess as sp
import shlex

def run(cmdline):
  process = sp.Popen(shlex.split(cmdline), stdout=sp.PIPE, stderr=sp.PIPE)
  output, err = process.communicate()
  retcode = process.poll()
  return retcode, output, err

run('./a.out '+arg1+' '+arg2+' '+...)
like image 146
log0 Avatar answered Oct 16 '22 02:10

log0