我正在使用boost :: python将一些python代码嵌入到应用程序中.我能够正确评估print语句或其他表达式,但是当我尝试导入模块时,它不是导入而应用程序正在退出.此外,嵌入式代码中的globals()函数调用也会产生运行时错误.
#include <boost/python.hpp>
using namespace boost;
using namespace boost::python;
using namespace boost::python::api;
int main(void) {
Py_Initialize();
object main_module = import("__main__");
object main_namespace = main_module.attr("__dict__");
main_namespace["urllib2"] = import("urllib2");
object ignored = exec(
"print 'time'\n", main_namespace);
}
Run Code Online (Sandbox Code Playgroud)
在这里,我尝试使用boost import函数导入urllib2,这会编译并正常运行,但是使用以下exec语句,它会出错.
object ignored = exec(
"print urllib2\n"
"print 'time'\n", main_namespace);
Run Code Online (Sandbox Code Playgroud)
或者当我删除boost导入函数并从嵌入代码中进行导入时,它会出错.我尝试使用try:except:block但是这也不起作用.这是因为C++应用程序无法找到urllib2 py模块的位置或什么?有没有办法在尝试导入之前设置模块的路径?
这是为内部使用而构建的,因此可以接受一些路径的硬编码.
编辑:更多信息:
这就是发生的事情.我做了一次尝试..捕获并在有异常时调用PyErr_Print(),并且在模块导入甚至函数调用时始终将其作为错误.错误信息:
Traceback (most recent call last):
File "<string>", line 1, in <module>
TypeError: 'NoneType' object does not support item assignment
Run Code Online (Sandbox Code Playgroud)
谁能想到任何理由?
如果你还没有,你需要
import sys
sys.path.append("/home/user/whatever")
几年前嵌入boost :: python(Python v2.5)时,这解决了我的问题.
编辑:
用旧代码戳了戳.也许这就是诀窍:
Py_SetProgramName(argv[0]); Py_InitializeEx(0);
听起来不确定你真的需要它Py_SetProgramName(),但我依旧记得那里有些腥生意.
那没有帮助,但我找到了解决问题的不同方法。我当前的代码如下所示:
#include <boost/python.hpp>
#include <iostream>
using namespace std;
using namespace boost;
using namespace boost::python;
using namespace boost::python::api;
int main(void) {
Py_Initialize();
boost::python::object http = boost::python::import("urllib2");
try
{
boost::python::object response = http.attr("urlopen")("http://www.google.com");
boost::python::object read = response.attr("read")();
std::string strResponse = boost::python::extract<string>(read);
cout << strResponse << endl;
}
catch(...)
{
PyErr_Print();
PyErr_Clear();
}
}
Run Code Online (Sandbox Code Playgroud)
无论如何,感谢乔纳斯的回答