问题概述
我正在开发一个自己的Python C扩展程序,以提高特定代码段的性能。我想调试这个扩展程序,但是到目前为止我还没有成功。我已经尝试了一些链接,比如这个来自Nadiah的链接或这个来自Bark的链接,但我总是遇到同样的问题:我无法在C代码的任何断点处停止。
我尝试的方法
想法是将Python作为主进程运行,并将编译后的C代码附加到该主进程上。以下是最小可再现示例:
Python文件
import os
import greet
pid = os.getpid()
test=2.2
greet.greet('World')
print("hi")
如您所见,我甚至检索了进程ID,以便在附加C代码时可以选择此ID。C代码如下:
C代码
#include <Python.h>
static PyObject *
greet_name(PyObject *self, PyObject *args)
{
const char *name;
if (!PyArg_ParseTuple(args, "s", &name))
{
return NULL;
}
printf("Helllo %s!\n", name);
Py_RETURN_NONE;
}
static PyMethodDef GreetMethods[] = {
{"greet", greet_name, METH_VARARGS, "Greet an entity."},
{NULL, NULL, 0, NULL}
};
static struct PyModuleDef greet =
{
PyModuleDef_HEAD_INIT,
"greet", /* name of module */
"", /* module documentation, may be NULL */
-1, /* size of per-interpreter state of the module, or -1 if the module keeps state in global variables. */
GreetMethods
};
PyMODINIT_FUNC PyInit_greet(void)
{
return PyModule_Create(&greet);
}
我使用GCC 8.1编译C代码,通过运行python setup.py install命令:
安装文件
import os
from setuptools import setup, Extension
os.environ["CC"] = "g++-8.1.0"
_DEBUG = True
_DEBUG_LEVEL = 0
# extra_compile_args = sysconfig.get_config_var('CFLAGS').split()
extra_compile_args = ["-Wall", "-Wextra"]
if _DEBUG:
extra_compile_args += ["-g3", "-O0", "-DDEBUG=%s" % _DEBUG_LEVEL, "-UNDEBUG"]
else:
extra_compile_args += ["-DNDEBUG", "-O3"]
setup(
name='greet',
version='1.0',
description='Python Package with Hello World C Extension',
ext_modules=[
Extension(
'greet',
sources=['greetmodule.c'],
py_limited_api=True,
extra_compile_args=extra_compile_args)
],
)
我甚至使用O0选项来拥有所有调试符号。
启动JSON文件
"configurations": [
{
"name": "(gdb) Attach",
"type": "cppdbg",
"request": "attach",
"program": "venv/Scripts/python",
"processId": "${command:pickProcess}",
"MIMode": "gdb",
// "miDebuggerPath": "/path/to/gdb",
"setupCommands": [
{
"description": "Enable pretty-printing for gdb",
"text": "-enable-pretty-printing",
"ignoreFailures": true
}
]
},
{
"name": "Python: Current File",
"type": "python",
"request": "launch",
"program": "${file}",
"console": "integratedTerminal"
}
]
我遵循的调试步骤
- 在Python文件中添加断点,运行启动配置“Python: Current File”,等待到达断点。
- 运行“(gdb) Attach”启动配置,选择路径包含“/.vscode/”的Python解释器。在这种情况下,在Windows中,不会像在Linux中那样提示输入用户密码。
- 在C ++文件中设置断点。
- Python调试器当前停止在断点处。从调试器“(gdb) Attach”切换回另一个调试器“Python: Current File”,然后按F5(继续)。
在这最后一步中,vscode应该自动在Python和C++代码之间跳转两个调试器,但我无法实现此行为。
我能够单独调试Python和C程序,但无法共同调试。
benjamin-simmonds.pythoncpp-debug? - starball