c++中嵌入式python的Matplotlib和子解释器

Matplotlib and subinterpreter for embedded python in c++

本文关键字:解释器 Matplotlib 嵌入式 python c++      更新时间:2023-10-16

我刚刚在我的c++嵌入式python编辑器中添加了子解释器,以便每次执行都有一个干净的解释器。

  PyThreadState* tmpstate = Py_NewInterpreter();
  PyThreadState_Swap(tmpstate);
  ... run the script ...
  Py_EndInterpreter(tmpstate);

我自己的模块正在工作,我测试numpy没有任何问题。问题在于matplotlib

如果我第一次运行,一切看起来都很好。第二次我得到:

<class 'TypeError'>: attribute of type 'NoneType' is not callable:   File "<string>", line 1, in <module>
  File "C:Python33libsite-packagespylab.py", line 1, in <module>
from matplotlib.pylab import *
  File "C:Python33libsite-packagesmatplotlib__init__.py", line 152, in <module>
from matplotlib.rcsetup import (defaultParams,
  File "C:Python33libsite-packagesmatplotlibrcsetup.py", line 19, in <module>
from matplotlib.fontconfig_pattern import parse_fontconfig_pattern
  File "C:Python33libsite-packagesmatplotlibfontconfig_pattern.py", line 25, in <module>
from matplotlib.pyparsing_py3 import Literal, ZeroOrMore, 
  File "C:Python33libsite-packagesmatplotlibpyparsing_py3.py", line 3275, in <module>
_escapedHexChar = Combine( Suppress(_bslash + "0x") + Word(hexnums) ).setParseAction(lambda s,l,t:unichr(int(t[0],16)))
   File "C:Python33libsite-packagesmatplotlibpyparsing_py3.py", line 2961, in __init__
self.leaveWhitespace()
File "C:Python33libsite-packagesmatplotlibpyparsing_py3.py", line 2587, in      leaveWhitespace
self.expr = self.expr.copy()
  File "C:Python33libsite-packagesmatplotlibpyparsing_py3.py", line 705, in copy
cpy = copy.copy( self )
  File "C:Python33libcopy.py", line 89, in copy
rv = reductor(2)

这似乎是Python 3.3中的一个错误:http://bugs.python.org/issue17408

问题是:

The reason is in Objects/typeobject.c: import_copyreg() has a static cache of the copyreg      module.
When the interpreter stops, the module is filled with None... but gets reused in the next     instance.
Resetting this "mod_copyreg" variable to NULL fixes the issue.
pickle is also broken for the same reason.