Я пытаюсь создать простой отладчик Python на C++, вызывая pdb. Я могу вызвать «runcall» pdb для файла Python из C++, но кажется, что последующий ввод не обрабатывается как команды pdb. Ниже приведен файл Python, пример кода C++, который настраивает встроенный Python и перенаправляет stdio, и, наконец, вывод при его запуске.
(извините за форматирование — ctrl-M, кажется, всегда объединяет последние два блока и текст между ними, что бы я ни пытался).
Сначала файл Python:
#
def test() :
a = 1
b = 2
print('sum is', a+b)
Далее код C++:
#ifdef _DEBUG
#undef _DEBUG
#include
#define _DEBUG
#else
#include
#endif
#include
//***************************************************************************//
// output to stdout
static PyObject* output(PyObject* self, PyObject* args)
{
char* string;
if (!PyArg_ParseTuple(args, "s", &string))
return 0;
printf("%s", string);
return Py_BuildValue("");
}
//***************************************************************************//
// read from stdio, echoing to output.
static PyObject* input(PyObject* self, PyObject* args)
{
char string[64] = {};
scanf(string);
printf("%s", string);
return PyBytes_FromString(string);
}
//***************************************************************************//
// flush stdout
static PyObject* flush(PyObject* self, PyObject* args)
{
fflush(stdout);
return Py_BuildValue("");
}
//***************************************************************************//
// method defs
static PyMethodDef ioMethods[] = {
{"output", output, METH_VARARGS, "output"},
{"input", input, METH_VARARGS, "input"},
{"flush", flush, METH_VARARGS, "flush"},
{NULL, NULL, 0, NULL}
};
//***************************************************************************//
// module def
static PyModuleDef cModPyUiApi =
{
PyModuleDef_HEAD_INIT,
"uiapi", /* name of module */
"The SWIG API", /* module documentation, may be NULL */
-1, /* size of per-interpreter state of the module, */
/* or -1 if the module keeps state in global variables. */
ioMethods /* the PyMethodDef methods */
};
//***************************************************************************//
// module init
PyMODINIT_FUNC PyInit_UiApi(void)
{
return PyModule_Create(&cModPyUiApi);
}
//***************************************************************************//
// main
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);
// Initialise the Python interpreter IO methods
int ok = PyImport_AppendInittab("uiapi", &PyInit_UiApi);
Py_Initialize();
// Redirect Python stdio
const char* code =
"class Sout:\n"
"\tdef write(self, s):\n"
"\t\toutput(s)\n"
"\tdef flush(self):\n"
"\t\tflush(self)\n"
"\tdef readline(self):\n"
"\t\treturn input(self)\n"
"\n"
"class Sin:\n"
"\tdef readline(self):\n"
"\t\treturn input(self)\n"
"\n"
"import sys\n"
"from uiapi import *\n"
"sys.stdout = Sout()\n"
"sys.stderr = Sout()\n"
"sys.stdin = Sin()\n";
ok = PyRun_SimpleString(code);
if (ok != 0) {
printf("Initialising Python stdio failed!\n");
}
// Create dicts for globals and locals
PyObject* main_module = PyImport_AddModule("__main__");
PyObject* locals = PyModule_GetDict(main_module);
PyObject* globals = PyModule_GetDict(main_module);
PyDict_SetItemString(globals, "__builtins__", PyEval_GetBuiltins());
// Evaluate python code and get the result
(void) PyRun_String("import pdb", Py_file_input, globals, locals);
(void) PyRun_String("import test", Py_file_input, globals, locals);
// run the test.py file under pdb
(void)PyRun_String("pdb.runcall(test.test)", Py_file_input, globals, locals);
// do some single stepping
(void)PyRun_String("s", Py_file_input, globals, locals);
(void)PyRun_String("s", Py_file_input, globals, locals);
(void)PyRun_String("s", Py_file_input, globals, locals);
// check whether the above caused any error
if (PyErr_Occurred()) {
PyErr_Print(); PyErr_Clear(); return 1;
}
return 0;
}
И наконец, результат:
> c:\users\keith\desktop\test.py(3)test()
-> a = 1
(Pdb)
Traceback (most recent call last):
File "", line 1, in
NameError: name 's' is not defined
Подробнее здесь: https://stackoverflow.com/questions/798 ... read-input
Запуск pdb во встроенном Python не читает ввод ⇐ C++
Программы на C++. Форум разработчиков
-
Anonymous
1772199182
Anonymous
Я пытаюсь создать простой отладчик Python на C++, вызывая pdb. Я могу вызвать «runcall» pdb для файла Python из C++, но кажется, что последующий ввод не обрабатывается как команды pdb. Ниже приведен файл Python, пример кода C++, который настраивает встроенный Python и перенаправляет stdio, и, наконец, вывод при его запуске.
(извините за форматирование — ctrl-M, кажется, всегда объединяет последние два блока и текст между ними, что бы я ни пытался).
Сначала файл Python:
#
def test() :
a = 1
b = 2
print('sum is', a+b)
Далее код C++:
#ifdef _DEBUG
#undef _DEBUG
#include
#define _DEBUG
#else
#include
#endif
#include
//***************************************************************************//
// output to stdout
static PyObject* output(PyObject* self, PyObject* args)
{
char* string;
if (!PyArg_ParseTuple(args, "s", &string))
return 0;
printf("%s", string);
return Py_BuildValue("");
}
//***************************************************************************//
// read from stdio, echoing to output.
static PyObject* input(PyObject* self, PyObject* args)
{
char string[64] = {};
scanf(string);
printf("%s", string);
return PyBytes_FromString(string);
}
//***************************************************************************//
// flush stdout
static PyObject* flush(PyObject* self, PyObject* args)
{
fflush(stdout);
return Py_BuildValue("");
}
//***************************************************************************//
// method defs
static PyMethodDef ioMethods[] = {
{"output", output, METH_VARARGS, "output"},
{"input", input, METH_VARARGS, "input"},
{"flush", flush, METH_VARARGS, "flush"},
{NULL, NULL, 0, NULL}
};
//***************************************************************************//
// module def
static PyModuleDef cModPyUiApi =
{
PyModuleDef_HEAD_INIT,
"uiapi", /* name of module */
"The SWIG API", /* module documentation, may be NULL */
-1, /* size of per-interpreter state of the module, */
/* or -1 if the module keeps state in global variables. */
ioMethods /* the PyMethodDef methods */
};
//***************************************************************************//
// module init
PyMODINIT_FUNC PyInit_UiApi(void)
{
return PyModule_Create(&cModPyUiApi);
}
//***************************************************************************//
// main
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);
// Initialise the Python interpreter IO methods
int ok = PyImport_AppendInittab("uiapi", &PyInit_UiApi);
Py_Initialize();
// Redirect Python stdio
const char* code =
"class Sout:\n"
"\tdef write(self, s):\n"
"\t\toutput(s)\n"
"\tdef flush(self):\n"
"\t\tflush(self)\n"
"\tdef readline(self):\n"
"\t\treturn input(self)\n"
"\n"
"class Sin:\n"
"\tdef readline(self):\n"
"\t\treturn input(self)\n"
"\n"
"import sys\n"
"from uiapi import *\n"
"sys.stdout = Sout()\n"
"sys.stderr = Sout()\n"
"sys.stdin = Sin()\n";
ok = PyRun_SimpleString(code);
if (ok != 0) {
printf("Initialising Python stdio failed!\n");
}
// Create dicts for globals and locals
PyObject* main_module = PyImport_AddModule("__main__");
PyObject* locals = PyModule_GetDict(main_module);
PyObject* globals = PyModule_GetDict(main_module);
PyDict_SetItemString(globals, "__builtins__", PyEval_GetBuiltins());
// Evaluate python code and get the result
(void) PyRun_String("import pdb", Py_file_input, globals, locals);
(void) PyRun_String("import test", Py_file_input, globals, locals);
// run the test.py file under pdb
(void)PyRun_String("pdb.runcall(test.test)", Py_file_input, globals, locals);
// do some single stepping
(void)PyRun_String("s", Py_file_input, globals, locals);
(void)PyRun_String("s", Py_file_input, globals, locals);
(void)PyRun_String("s", Py_file_input, globals, locals);
// check whether the above caused any error
if (PyErr_Occurred()) {
PyErr_Print(); PyErr_Clear(); return 1;
}
return 0;
}
И наконец, результат:
> c:\users\keith\desktop\test.py(3)test()
-> a = 1
(Pdb)
Traceback (most recent call last):
File "", line 1, in
NameError: name 's' is not defined
Подробнее здесь: [url]https://stackoverflow.com/questions/79897804/running-pdb-in-embedded-python-doesnt-read-input[/url]
Ответить
1 сообщение
• Страница 1 из 1
Перейти
- Кемерово-IT
- ↳ Javascript
- ↳ C#
- ↳ JAVA
- ↳ Elasticsearch aggregation
- ↳ Python
- ↳ Php
- ↳ Android
- ↳ Html
- ↳ Jquery
- ↳ C++
- ↳ IOS
- ↳ CSS
- ↳ Excel
- ↳ Linux
- ↳ Apache
- ↳ MySql
- Детский мир
- Для души
- ↳ Музыкальные инструменты даром
- ↳ Печатная продукция даром
- Внешняя красота и здоровье
- ↳ Одежда и обувь для взрослых даром
- ↳ Товары для здоровья
- ↳ Физкультура и спорт
- Техника - даром!
- ↳ Автомобилистам
- ↳ Компьютерная техника
- ↳ Плиты: газовые и электрические
- ↳ Холодильники
- ↳ Стиральные машины
- ↳ Телевизоры
- ↳ Телефоны, смартфоны, плашеты
- ↳ Швейные машинки
- ↳ Прочая электроника и техника
- ↳ Фототехника
- Ремонт и интерьер
- ↳ Стройматериалы, инструмент
- ↳ Мебель и предметы интерьера даром
- ↳ Cантехника
- Другие темы
- ↳ Разное даром
- ↳ Давай меняться!
- ↳ Отдам\возьму за копеечку
- ↳ Работа и подработка в Кемерове
- ↳ Давай с тобой поговорим...
Мобильная версия