У меня возникла проблема с вызовом простого скрипта 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
Функция Python, вызываемая из C++, не определена ⇐ Python
Программы на Python
-
Anonymous
1772017644
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;
}
Подробнее здесь: [url]https://stackoverflow.com/questions/79896076/python-func-called-from-c-not-defined[/url]
Ответить
1 сообщение
• Страница 1 из 1
Перейти
- Кемерово-IT
- ↳ Javascript
- ↳ C#
- ↳ JAVA
- ↳ Elasticsearch aggregation
- ↳ Python
- ↳ Php
- ↳ Android
- ↳ Html
- ↳ Jquery
- ↳ C++
- ↳ IOS
- ↳ CSS
- ↳ Excel
- ↳ Linux
- ↳ Apache
- ↳ MySql
- Детский мир
- Для души
- ↳ Музыкальные инструменты даром
- ↳ Печатная продукция даром
- Внешняя красота и здоровье
- ↳ Одежда и обувь для взрослых даром
- ↳ Товары для здоровья
- ↳ Физкультура и спорт
- Техника - даром!
- ↳ Автомобилистам
- ↳ Компьютерная техника
- ↳ Плиты: газовые и электрические
- ↳ Холодильники
- ↳ Стиральные машины
- ↳ Телевизоры
- ↳ Телефоны, смартфоны, плашеты
- ↳ Швейные машинки
- ↳ Прочая электроника и техника
- ↳ Фототехника
- Ремонт и интерьер
- ↳ Стройматериалы, инструмент
- ↳ Мебель и предметы интерьера даром
- ↳ Cантехника
- Другие темы
- ↳ Разное даром
- ↳ Давай меняться!
- ↳ Отдам\возьму за копеечку
- ↳ Работа и подработка в Кемерове
- ↳ Давай с тобой поговорим...
Мобильная версия