Функция Python, вызываемая из C++, не определенаPython

Программы на Python
Ответить
Anonymous
 Функция Python, вызываемая из C++, не определена

Сообщение Anonymous »

У меня возникла проблема с вызовом простого скрипта Python из C++. У меня есть простой тестовый пример, иллюстрирующий проблему; В скрипте Python функция func fb должна вызывать fa, которая была определена ранее.
Однако я получаю сообщение об ошибке:
Вызывается fb
Traceback (most recent call last):
File "", line 1, in
File "", line 13, in
File "", line 10, in fb
NameError: name 'fa' is not defined

Файл test.py:
def fa() :
print('Called fa')
return 3
def fb() :
print('Called fb')
return fa() * 2
fb()
print('Finished test.py')

Код C++:
#ifdef _DEBUG
#undef _DEBUG
#include
#define _DEBUG
#else
#include
#endif
#include
int main() {

// Initialize the python interpreter, setting path
const char * app_path = "C:\\Python383-x64\\";
size_t convertedChars = 0;
size_t newsize = strlen(app_path);
wchar_t* wcstring = new wchar_t[newsize];
mbstowcs_s(&convertedChars, wcstring, newsize, app_path, _TRUNCATE);
Py_SetPythonHome(wcstring);
Py_Initialize();

// Create dicts for globals and locals
PyObject* globals = PyDict_New();
PyObject* locals = PyDict_New();

// Set the builtins
PyDict_SetItemString(globals, "__builtins__", PyEval_GetBuiltins());

// Evaluate python code and get the result
PyObject* string_result = PyRun_String("exec(open(\"test.py\").read())", Py_single_input, globals, locals);

// check whether the python code caused any Exception
if (PyErr_Occurred()) {
PyErr_Print(); PyErr_Clear(); return 1;
}
else {
// print the result
PyObject_Print(string_result, stdout, Py_PRINT_RAW);
}
return 0;
}


Подробнее здесь: https://stackoverflow.com/questions/798 ... ot-defined
Ответить

Быстрый ответ

Изменение регистра текста: 
Смайлики
:) :( :oops: :roll: :wink: :muza: :clever: :sorry: :angel: :read: *x)
Ещё смайлики…
   
К этому ответу прикреплено по крайней мере одно вложение.

Если вы не хотите добавлять вложения, оставьте поля пустыми.

Максимально разрешённый размер вложения: 15 МБ.

Вернуться в «Python»