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

Posted

技术标签:

【中文标题】Matplotlib 和 C++ 中嵌入式 python 的子解释器【英文标题】:Matplotlib and subinterpreter for embedded python in c++ 【发布时间】:2013-04-12 07:54:06 【问题描述】:

我刚刚在我的 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:\Python33\lib\site-packages\pylab.py", line 1, in <module>
from matplotlib.pylab import *

  File "C:\Python33\lib\site-packages\matplotlib\__init__.py", line 152, in <module>
from matplotlib.rcsetup import (defaultParams,

  File "C:\Python33\lib\site-packages\matplotlib\rcsetup.py", line 19, in <module>
from matplotlib.fontconfig_pattern import parse_fontconfig_pattern

  File "C:\Python33\lib\site-packages\matplotlib\fontconfig_pattern.py", line 25, in <module>
from matplotlib.pyparsing_py3 import Literal, ZeroOrMore, \

  File "C:\Python33\lib\site-packages\matplotlib\pyparsing_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:\Python33\lib\site-packages\matplotlib\pyparsing_py3.py", line 2961, in __init__
self.leaveWhitespace()

File "C:\Python33\lib\site-packages\matplotlib\pyparsing_py3.py", line 2587, in      leaveWhitespace
self.expr = self.expr.copy()

  File "C:\Python33\lib\site-packages\matplotlib\pyparsing_py3.py", line 705, in copy
cpy = copy.copy( self )

  File "C:\Python33\lib\copy.py", line 89, in copy
rv = reductor(2)

【问题讨论】:

【参考方案1】:

这似乎是 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.

【讨论】:

以上是关于Matplotlib 和 C++ 中嵌入式 python 的子解释器的主要内容,如果未能解决你的问题,请参考以下文章

opencv-PIL-matplotlib-Skimage-Pytorch图片读取区别与联系

从 C++ 嵌入式解释器捕获 python 窗口输出

将 Matplotlib 图形嵌入到小部件中 - PyQt5

将matplotlib嵌入到tkinter应用程序中

如何在 pyqt 中嵌入 matplotlib - For Dummies

如何在 pyqt 中嵌入 matplotlib - For Dummies