Steps and cases of dynamically debugging python source code

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:

  1. Download the source code of cpython, the author downloaded the source code of python3.10.4 from reference 2

  2. Double-click (with Visual Studio) to open the PCbuild/pcbuild.sln file in the source code directory

  3. VS is set to Debug, Win32 mode

  4. 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
    insert image description here

  5. 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:
    insert image description here

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?

  1. 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
  2. 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

  1. https://github.com/python/cpython
  2. https://github.com/python/cpython/releases/tag/v3.10.4
  3. https://github.com/python/cpython/blob/8a0d9a6bb77a72cd8b9ece01b7c1163fff28029a/Python/pythonrun.c#L136

Guess you like

Origin blog.csdn.net/ybdesire/article/details/125465265