我在瞎折腾,试图制造类似IPython/Jupyter笔记本的东西。我在QT5中编写我的应用程序,这其中大部分与在本机应用程序中“嵌入”Python有关。在
我发现了如何嵌入python以及如何允许它执行用户输入的脚本。我希望能够使用打印库(如matplotlib),并在我的应用程序中显示它们的输出。(事实上,我要做的事情似乎与this question中描述的非常相似)。在
但是,当我试图使用import matplotlib.pyplot导入绘图库时,我的应用程序出现了错误(我尝试了调试,但崩溃不在我的代码中,因此我无法从中得到任何合理的结果)。在
我用来初始化嵌入式Python和运行任意脚本的代码显示在这个问题的底部。在
我可以很好地导入其他库(例如sys或numpy)。我可以很好地导入matplotlib。但是当我试图导入matplotlib.pyplot时,它会出错。在
有人有什么建议吗?在
编辑:
我已经确定原因在于(出于某种原因)我使用QT。当我编译一个简单的C或C++程序导入MatpTLIB时,它就没有< EM>不是EEM> SeGebug…在
我的代码:#include "pythoninteractor.h"
#include
#include
#include
#include
PythonInteractor::PythonInteractor()
{
this->pyOutput_redir =
"import sys\n\
class CatchOutErr:\n\
def __init__(self):\n\
self.value = ''\n\
def write(self, txt):\n\
self.value += txt\n\
catchOutErr = CatchOutErr()\n\
sys.stdout = catchOutErr\n\
sys.stderr = catchOutErr\n\
"; //this is python code to redirect stdouts/stderr
QString paths[] = {"",
"/home/tcpie/anaconda3/lib/python35.zip",
"/home/tcpie/anaconda3/lib/python3.5",
"/home/tcpie/anaconda3/lib/python3.5/plat-linux",
"/home/tcpie/anaconda3/lib/python3.5/lib-dynload",
"/home/tcpie/anaconda3/lib/python3.5/site-packages",};
Py_SetProgramName(L"qt-notepad-tut");
Py_Initialize();
PyObject *pModule = PyImport_AddModule("__main__"); //create main module
PyRun_SimpleString(this->pyOutput_redir.toStdString().c_str()); //invoke code to redirect
PyObject *sys_path;
PyObject *path;
sys_path = PySys_GetObject("path");
if (sys_path == NULL)
return;
PySequence_DelSlice(sys_path, 0, PySequence_Length(sys_path));
for (size_t i = 0; i < sizeof(paths) / sizeof(QString); i++) {
path = PyUnicode_FromString(paths[i].toStdString().c_str());
if (path == NULL)
continue;
if (PyList_append(sys_path, path) < 0)
continue;
}
}
QString PythonInteractor::run_script(QString script)
{
QString ret = "";
PyObject *pModule = PyImport_AddModule("__main__");
PyRun_SimpleString(script.toStdString().c_str());
PyErr_Print(); //make python print any errors
PyObject *catcher = PyObject_GetAttrString(pModule,"catchOutErr"); //get our catchOutErr created above
if (catcher == NULL) {
Py_Finalize();
return ret;
}
PyObject *output = PyObject_GetAttrString(catcher,"value"); //get the stdout and stderr from our catchOutErr object
if (output == NULL) {
return ret;
}
ret = QString(PyUnicode_AsUTF8(output));
return ret;
}