0

Using Py_Initialize(), we can start the python interpreter in a C++ program. However as the function does not return anything, we cannot use the same interpreter in a different program. Is there any way of calling Py_Initialize() in one C++ program, make the interpreter persistent and use it in a different C++ program(without calling Py_Initialize() again)?

Edit: To be more specific, Is there a way can get hold of an instance of a python interpreter and pass it to another execution as a parameter and use it to run python scripts.

  • If it's a different program, it's, by definition, not the same interpreter instance. – spectras Feb 08 '17 at 09:55
  • 2
    There is no such thing as a "C/C++ program". Decide which language you are using. If it is C, then remove the C++ tag. – Lundin Feb 08 '17 at 09:59

1 Answers1

1

No. The CPython interpreter itself does not work like that. There is no distinct interpreter object, but rather a floating set of globals with a stateful API. What's worse, Python code can load arbitrary other libraries, whose state can definitely not be persisted (in general).

What you can do is to pickle the existing variables. That can sometimes bring you somewhere close. That is not really a hosting problem, but a Python problem. Naturally, though, you could make sure that your C code hosting Python made sure to execute the serializations steps after the "real" Python code has finished executing. Something like How can I save all the variables in the current python session? might be a starting point.

Community
  • 1
  • 1
cnettel
  • 1,024
  • 5
  • 7