1. Import
The source code cpython of the c language version of python can be downloaded from github (see reference 1).
So how to run and debug this source code?
2. Steps to debug cpython
The author uses Visual Studio Community2019 to debug on Windows 10, the steps are as follows:
-
Download the source code of cpython, the author downloaded the source code of python3.10.4 from reference 2
-
Double-click (with Visual Studio) to open the PCbuild/pcbuild.sln file in the source code directory
-
VS is set to Debug, Win32 mode
-
In Solution, right click, select properties, select Configuration Properties, select Configuration, how to select Build and only select python and pythoncore, as shown in the following figure
-
Then run debug directly to debug. The interface obtained after running is exactly the same as the interface obtained by directly running the python command, as shown in the following figure:
3. Simple debugging case
We know that in the python shell, after entering a statement, it will be executed to get the result, and then another statement will be executed to get the result. It can be input and executed all the time like an infinite loop. So what does this process look like in the source code?
- First find the location of the main function, which can be found according to the Startup Project (black font) of VS. The main function of the C language is located in Program/python.c
- Enter from the main function, add a breakpoint, and single-step debugging, you can enter Python/pythonrun.c, the simplified source code is as follows, see reference 3 for details
int _PyRun_InteractiveLoopObject()
{
do {
//在这个循环中,运行交互式语句
ret = PyRun_InteractiveOneObjectEx(fp, filename, flags);
} while (ret != E_EOF);
return err;
}
4. Summary
Using Visual Studio Community2019 on Windows 10, you can debug the python source code. The python source code also comes with a .sln file suitable for VS to open and open, which is very convenient for debugging.
reference
- https://github.com/python/cpython
- https://github.com/python/cpython/releases/tag/v3.10.4
- https://github.com/python/cpython/blob/8a0d9a6bb77a72cd8b9ece01b7c1163fff28029a/Python/pythonrun.c#L136