When you execute a Python program, you will find that your function is very simple, such as printing from 1 to 10 and then printing out the File mode, the execution of Python programs and interactions are all in this type. The following is a detailed description of the article. Forget that you will get something.
Python source code analysis 2-a simple Python program execution favorites
This article describes the basic framework and structure of Python implementation by tracking the execution of a very simple Python program.
To execute the Python program as follows, the function is very simple: Add 1 to 10 and print it out.
- # test program
- sum = 0
- for i in range(1, 11):
- sumsum = sum + i
- print sum
To debug Python with VS 2005 in Windows, follow these steps:
Set the Startup Project to Python, so that you can start Python directly through F5 right-click the Python Project and select Properties. Under Configuration Properties> Debugging in the dialog box, SET Command Arguments to-d test. py. Test. py is the name of the program to be debugged. -D indicates that the debug switch is enabled and additional debugging information is displayed.
Well, after setting, you can directly press F10 to track the execution of the program in a single step.
First, F10, start the Python program, you can see that there is nothing in the main function of Python, just a simple call to Py_Main. Py_Main, as its name implies, is naturally the main function, which is divided into several parts:
Analyze command lines and Environment Variables
Call Py_Initialize for initialization
Enter different execution modes based on the command line content.
- if (command) {
- sts = PyRun_SimpleStringFlags(command, &cf) != 0;
- free(command);
- } else if (module) {
- sts = RunModule(module);
- free(module);
- }
- else {
- if (filename == NULL && stdin_is_interactive) {
- RunStartupFile(&cf);
- }
- /* XXX */
- sts = PyRun_AnyFileExFlags(
- fp,
- filename == NULL ? "<stdin>" : filename,
- filename != NULL, &cf) != 0;
- }
From the code above, we can easily see that there are three execution methods:
Command mode. Execute a single Python statement. Use-c to specify. The statement content is stored in the command variable. Call PyRun_SimpleStringFlags for execution.
Run the entire Module. Use-m to specify. Call RunModule for execution.
In File mode, the execution of Python programs and interactions are all in this class. We can see that if no file name is specified and stdin is interactive, a program specified by PYTHONSTARTUP will be executed.