用C ++嵌入Python

时间:2017-03-01 16:42:09

标签: python c++ python-3.x

问题:使用C ++嵌入Python时会引发奇怪的异常。

程序:

long

上面的代码片段应该做什么:该函数应首先检查传递的参数是否是python文件的有效位置。如果该文件存在,那么它应该执行Python文件。

我得到了预期的结果:是和否。

出了什么问题:

测试文件1:

HZ

结果:成功执行并获得正确的输出

测试文件2:

bool embedd::execute_python(std::string location)
{
    if (std::ifstream(location))
    {
            const char* file_location = location.c_str();
            FILE* file_pointer;
            // Initialize the Python interpreter
            Py_Initialize();
            file_pointer = _Py_fopen(file_location, "r");
            // Run the Python file
            PyRun_SimpleFile(file_pointer, file_location);
            // Finalize the Python interpreter
            Py_Finalize();
        return true;
    }
    return false;
}
  

结果:异常root = Tk()文件   " C:\用户\用户\应用程序数据\本地\程序\的Python \ Python35-32 \ LIB \ tkinter__init __ PY&#34 ;,   第1863行,在 init baseName = os.path.basename(sys.argv [0])中   AttributeError:module' sys'没有属性' argv'

使用其他一些文件测试,发现当我们导入模块(任何)时,如tkinter,uuid,os等类似的异常被抛出。简要介绍一下我的IDE的进程监视器告诉"符号文件未加载"例如没有为tk86t.dll加载符号文件

Python版本:3.5.2

我所提到的链接: SO - 1发现此错误已在Python 2.3中修复BUGS

1 个答案:

答案 0 :(得分:2)

一方面,由于某些原因,您的测试文件2会导入需要有效命令行的Tk(例如,对于Windows class Whatever extends React.Component { constructor(props) { super(props); this.state = { updatedPupilName: props.activePupil.name }; this.handleChange= this.handleChange.bind(this); } componentWillReceiveProps(nextProps) { if (nextProps.activePupil.name !== this.props.activePupil.name) { this.setState({ updatedPupilName: nextProps.activePupil.name }); } } handleChange(event) { this.setState({ updatedPupilName: event.target.value }); } render() { return ( <input type="text" value={this.state.updatedPupilName} onChange={this.handleChange} /> ); } } )。另一方面,你嵌入了python,因此没有命令行。这就是python抱怨的内容(&#34;模块&#39; sys&#39;没有属性&#39; argv&#39;&#34;)。您应该在Py_Initialize()之后直接创建一个伪命令行,例如:

C:\>python script.py -yourarguments

您的测试文件1不会导入Tk,因此不会期望有效的命令行。这就是没有上述代码的原因。