gpt4 book ai didi

python - 刷新 C 嵌入式 python 中的导入

转载 作者:行者123 更新时间:2023-11-30 17:27:03 25 4
gpt4 key购买 nike

我有一个 C 代码,其中使用“Python.h”嵌入了 python,它工作正常,没有任何错误 - 但它并没有完全按照我想要的方式进行。

它的作用:C 代码开始运行后,它会忽略我对 python 文件所做的所有更改,直到我重新启动 C 代码。

我想要什么:当 C 代码运行时,如果我对 python 文件进行更改,它应该开始运行新代码。

我尝试在调用该函数之前每次都使用该函数PyImport_ReloadModule,但它不起作用。我做错了什么吗?

我当前的代码:

#include "Strategy.h"
#undef _DEBUG /* Link with python24.lib and not python24_d.lib */
#include <Python.h>
#include <stdlib.h>
#include <iostream>

using namespace std;
PyObject *pName, *pModule, *pDict, *pFunc;
PyObject *pArgs, *pValue;

void import_py() {
pName = PyString_FromString("main");
pModule = PyImport_Import(pName);
Py_DECREF(pName);
if (pModule == NULL) {
cout << "ERR : Unable to load main.py\n";
return;
} else {
cout << "OK : Loaded main.py\n";
}
if ( PyObject_HasAttrString(pModule, "main") ) {
cout << "OK : main.py has function main\n";
} else {
cout << "ERR : main.py has no function main\n";
return;
}
pFunc = PyObject_GetAttrString(pModule, "main");
if ( pFunc == NULL ) {
cout << "OK : main.py's function main gave NULL when trying to take it\n";
return;
}
}

void remove_py() {
Py_XDECREF(pArgs);
Py_XDECREF(pModule);
Py_XDECREF(pFunc);
Py_Finalize();
}

void Construct() {
Py_Initialize();
import_py();
}

void Destruct() {
if ( pModule || pFunc ) {
remove_py();
}
}


void Loop () {
if ( ! ( pModule && pFunc ) ) {
cout << "Looped. But python values are null\n";
return;
}
cout << "Loop : ";

pArgs = PyTuple_New(2); // Create a tuple to send to python - sends 1,2
PyTuple_SetItem(pArgs, 0, PyInt_FromLong(1));
PyTuple_SetItem(pArgs, 1, PyInt_FromLong(2));

pValue = PyObject_CallObject(pFunc, pArgs);
Py_DECREF(pArgs);

double t = 0; // Get the 2 return values
t = PyFloat_AsDouble(PyTuple_GetItem(pValue, 0));
cout << t << ", ";
t = PyFloat_AsDouble(PyTuple_GetItem(pValue, 1));
cout << t;

cout << "\n";
}

void main() {
Construct();
while(1) { // Using an infinite loop for now - to test
pModule = PyImport_ReloadModule(pModule);
Loop();
}
Destruct();
}

最佳答案

我发现了这个问题。

即使使用 pModule = PyImport_ReloadModule(pModule) 获取新模块后,p变量 pFunc 不会自动更新。因此,变量 pFunc 仍然引用旧模块!

因此,每个变量都需要重新获取。就像这样:

void main() {
Construct();
while(1) { // Using an infinite loop for now - to test
pModule = PyImport_ReloadModule(pModule);
pFunc = PyObject_GetAttrString(pModule, "main");
Loop();
}
Destruct();
}

我不确定的一件事是是否应该对引用旧 pModule 的 pFunc 进行 DECREF。

关于python - 刷新 C 嵌入式 python 中的导入,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26543648/

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