gpt4 book ai didi

c++ - 重复调用PyRun_SimpleFile出现Segmentation fault

转载 作者:行者123 更新时间:2023-11-30 04:46:40 26 4
gpt4 key购买 nike

我想在 c++ 中嵌入一个用 3.5 版编写的 python 代码。此外,python 脚本需要作为整个脚本重复执行。我的代码如下。它在第一次迭代时执行良好,在第二次迭代时给出段错误。

主要.cpp:

#include <Python.h>
#include<iostream>
using namespace std;

int main(int argc, char *argv[])
{
int i = 0;
while(i<3){
cout<<"start"<<endl;
Py_Initialize();
FILE* file;
wchar_t* _argv[argc];
for(int i=0; i<argc; i++){
wchar_t *arg = Py_DecodeLocale(argv[i], NULL);
_argv[i] = arg;
}

PySys_SetArgv(argc, _argv);
PyObject *sys = PyImport_ImportModule("sys");
PyObject *path = PyObject_GetAttrString(sys, "path");

PyList_Append(path, PyUnicode_FromString("."));
file = fopen("./example.py","r");
PyRun_SimpleFile(file, "./example.py");
fclose(file);
Py_Finalize();
cout<<"Done"<<endl;
i++;
}
return 0;
}

例子.py:

import tensorflow as tf

flags = tf.app.flags
FLAGS = flags.FLAGS

flags.DEFINE_float('learning_rate', 0.01, 'initial learning rate')

def main(argv=None):
print(FLAGS.learning_rate)

if __name__ == '__main__':
main()

我使用以下方法构建项目:cmake --build 。 --目标演示 -- -j 2并执行为:./Demo --learning_rate 0.02

输出是:

start
0.02
Done
start
Segmentation fault (core dumped)

然后我将“example.py”的内容替换为:print("嗨")

输出是:

start
Hi
Done
start
Hi
Done
start
Hi
Done

如何修复上述段错误?

最佳答案

参见 docs

Some extensions may not work properly if their initialization routine is called more than once; this can happen if an application calls Py_Initialize() and Py_Finalize() more than once.

关于c++ - 重复调用PyRun_SimpleFile出现Segmentation fault,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56632641/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com