在C+中嵌入Python+;:无法从同一目录导入
在一个更大的类中,我有一段代码用于导入python脚本并运行它。文件(animate.py)包含在与可执行文件相同的目录中在C+中嵌入Python+;:无法从同一目录导入,python,c++,Python,C++,在一个更大的类中,我有一段代码用于导入python脚本并运行它。文件(animate.py)包含在与可执行文件相同的目录中 void classname::show( void ) { stringstream run_cmd; run_cmd << "animate.run('" << name << "')"; Py_Initialize(); PyRun_SimpleString(
void classname::show( void )
{
stringstream run_cmd;
run_cmd << "animate.run('" << name << "')";
Py_Initialize();
PyRun_SimpleString("import animate");
PyRun_SimpleString(run_cmd.str().c_str());
Py_Finalize();
}
void classname::show(void)
{
stringstream run_cmd;
运行_cmd您需要将当前工作目录添加到Python路径(默认情况下不包括该目录):
这当然适用于能够导入脚本,但现在脚本无法导入numpy等。我也必须为此设置路径吗?而且我仍然很好奇,为什么这在另一台机器上可以正常工作,而不设置路径,但在这台机器上不行。
Traceback (most recent call last):
File "<string>", line 1, in <module>
ImportError: No module named animate
Traceback (most recent call last):
File "<string>", line 1, in <module>
NameError: name 'animate' is not defined
Py_Initialize();
PyObject *sys_path = PySys_GetObject("path");
PyList_Append(sys_path, PyString_FromString("."));
PyRun_SimpleString("import animate");
PyRun_SimpleString(run_cmd.str().c_str());
Py_Finalize();