Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
353 views
in Technique[技术] by (71.8m points)

c++ - Embedding python and running for multiple times

I'm using boost::python to embed python, this is how I do it:

void runCode(){
    Py_Initialize();
    //boost::python code goes here and embedded python code runs
    Py_Finalize();
}

it runs nicely for the first time, but when it is run again, I get this error:

LookupError: unknown encoding: utf8

and code does not run as expected, any help is appreciated.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Since you didn't get an expert answer, I'm offering my learning from working on a similar problem. Python have issues with reinitialization support. This is unfortunate if you need to restart the interpreter due to some error, or want to run many independent interpreters.

One issue there is leaking resources and memory (quoting from the above link):

Bugs and caveats: Dynamically loaded extension modules loaded by Python are not unloaded. Small amounts of memory allocated by the Python interpreter may not be freed (if you find a leak, please report it). Memory tied up in circular references between objects is not freed. Some memory allocated by extension modules may not be freed. Some extensions may not work properly if their initialization routine is called more than once; this can happen if an application calls Py_Initialize() and Py_Finalize() more than once.

Another issue is many modules don't support this properly, as can be seen for example in this SO thread. I think this is the problem you're facing.

It seems that most Python applications work-around this problem:

  • by having the engine run in a dedicated process ;
  • by using subinterpreters which represent distinct execution states (of a common interpreter)

If the second one works for you, go ahead with it.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...