-1

I have a c++ executable that performs a simulation and would like to use this simulation as my function for an optimization routine. My idea is to implement the optimization routine in python and glue python and the c++ executable together using a bash script.

Is this possible? Are there other approaches I should consider?

I have looked at creating a python extension module but the c++ project is large and I believe it will take far too long to implement this.

Botje
  • 26,269
  • 3
  • 31
  • 41
  • I believe boost.python does what you want (https://www.boost.org/doc/libs/1_39_0/libs/python/doc/index.html). Also try searching a bit this question has been asked a bunch on here. – cenh Sep 24 '19 at 12:47
  • 2
    any particular reason your python script can't run the c++ executable directly? – xception Sep 24 '19 at 12:50
  • 1
    You can use `subprocess.Popen` in Python to interact with external code via stdin/stdout. If you communicate via files, use `subprocess.run` and read the result. – Botje Sep 24 '19 at 12:51
  • @xception the executable is currently run from the terminal with some flags required to run, can this be done via python? – tristanmckechnie Sep 25 '19 at 09:47
  • absolutely can be done from python, and most programming languages I ever used, have a look at this question for how to do it https://stackoverflow.com/questions/7032212/how-to-run-application-with-parameters-in-python – xception Sep 25 '19 at 11:19
  • also have a look at https://stackoverflow.com/questions/4760215/running-shell-command-and-capturing-the-output/4760517#4760517 to see how you can get the output of a command you run directly from python – xception Sep 25 '19 at 11:26
  • @xception thanks for pointing me in the right direction! – tristanmckechnie Sep 26 '19 at 07:01

1 Answers1

0

Yes, this is possible - I have done it my self outputting the value of the onjective function to the terminal and parsing the output in python, calling the simulation as subprocess. Note that this can even be interfaced to batch submission systems if your simulations runs a long time. However, having a proper python interface only for the simulation function might be better - I can recommend https://github.com/pybind/pybind11 as an alternative to boost here.

Tobi
  • 76
  • 5