HomeBackend DevelopmentPython TutorialThe execution process of a Python program includes converting source code into bytecode (i.e. compilation) and executing the bytecode
The execution process of a Python program includes converting source code into bytecode (i.e. compilation) and executing the bytecode
We have to write some Python programs every day, either to process some text, or to do some system management work. After the program is written, you only need to type the python command to start the program and start executing it:
$ python some-program.py
Copy after login
So, how is a .py file in text form converted step by step into something that can be executed by the CPU? What about machine instructions? In addition, .pyc files may be generated during program execution. What are the functions of these files?
1. Execution process
Although Python looks more like an interpreted language like Shell script in terms of behavior, in fact, the execution principle of Python program is essentially the same as that of Java or C# and can be summarized For virtual machine and bytecode. Python executes the program in two steps: first compile the program code into bytecode, and then start the virtual machine to execute the bytecode:
Although the Python command is also called the Python interpreter , but it is fundamentally different from other scripting language interpreters. In fact, the Python interpreter consists of compiler and virtual machine. When the Python interpreter is started, it mainly performs the following two steps:
The compiler compiles the Python source code in the .py file into bytecode. The virtual machine executes the bytecode generated by the compiler line by line.
Therefore, the Python statements in the .py file are not directly converted into machine instructions, but into Python bytecode.
2. Bytecode
The compiled result of the Python program is bytecode, which contains a lot of content related to the operation of Python. Therefore, whether it is to have a deeper understanding of the operating mechanism of the Python virtual machine or to optimize the operating efficiency of the Python program, bytecode is the key content. So, what does Python bytecode look like? How can we obtain the bytecode of a Python program? Python provides a built-in function compile for instant compilation of source code. We only need to call the compile function with the source code to be compiled as a parameter to obtain the compilation result of the source code.
3. Source code compilation
Below, we compile a program through the compile function:
The source code is saved in the demo.py file:
PI = 3.14
def circle_area(r):
return PI * r ** 2
class Person(object):
def __init__(self, name):
self.name = name
def say(self):
print('i am', self.name)
Copy after login
Compile Previously, the source code needed to be read from the file:
>>> text = open('D:\myspace\code\pythonCode\mix\demo.py').read()
>>> print(text)
PI = 3.14
def circle_area(r):
return PI * r ** 2
class Person(object):
def __init__(self, name):
self.name = name
def say(self):
print('i am', self.name)
Copy after login
Then call the compile function to compile the source code:
>>> result = compile(text,'D:\myspace\code\pythonCode\mix\demo.py', 'exec')
Copy after login
There are 3 required parameters for the compile function:
source : Source code to be compiled
filename: file name where the source code is located
mode: compilation mode, exec means compiling the source code as a module
Three compilation modes:
exec: used to compile module source code
single: used to compile a single Python statement (interactively)
eval: used to compile an eval expression
4. PyCodeObject
Through the compile function, we get the final source code compilation result result:
>>> result
<code object <module> at 0x000001DEC2FCF680, file "D:\myspace\code\pythonCode\mix\demo.py", line 1>
>>> result.__class__
<class 'code'>
Copy after login
Finally we get a code type object, and its corresponding underlying structure is PyCodeObject
The source code of PyCodeObject is as follows:
/* Bytecode object */
struct PyCodeObject {
PyObject_HEAD
int co_argcount; /* #arguments, except *args */
int co_posonlyargcount; /* #positional only arguments */
int co_kwonlyargcount; /* #keyword only arguments */
int co_nlocals; /* #local variables */
int co_stacksize; /* #entries needed for evaluation stack */
int co_flags; /* CO_..., see below */
int co_firstlineno; /* first source line number */
PyObject *co_code; /* instruction opcodes */
PyObject *co_consts; /* list (constants used) */
PyObject *co_names; /* list of strings (names used) */
PyObject *co_varnames; /* tuple of strings (local variable names) */
PyObject *co_freevars; /* tuple of strings (free variable names) */
PyObject *co_cellvars; /* tuple of strings (cell variable names) */
/* The rest aren't used in either hash or comparisons, except for co_name,
used in both. This is done to preserve the name and line number
for tracebacks and debuggers; otherwise, constant de-duplication
would collapse identical functions/lambdas defined on different lines.
*/
Py_ssize_t *co_cell2arg; /* Maps cell vars which are arguments. */
PyObject *co_filename; /* unicode (where it was loaded from) */
PyObject *co_name; /* unicode (name, for reference) */
PyObject *co_linetable; /* string (encoding addr<->lineno mapping) See
Objects/lnotab_notes.txt for details. */
void *co_zombieframe; /* for optimization only (see frameobject.c) */
PyObject *co_weakreflist; /* to support weakrefs to code objects */
/* Scratch space for extra data relating to the code object.
Type is a void* to keep the format private in codeobject.c to force
people to go through the proper APIs. */
void *co_extra;
/* Per opcodes just-in-time cache
*
* To reduce cache size, we use indirect mapping from opcode index to
* cache object:
* cache = co_opcache[co_opcache_map[next_instr - first_instr] - 1]
*/
// co_opcache_map is indexed by (next_instr - first_instr).
// * 0 means there is no cache for this opcode.
// * n > 0 means there is cache in co_opcache[n-1].
unsigned char *co_opcache_map;
_PyOpcache *co_opcache;
int co_opcache_flag; // used to determine when create a cache.
unsigned char co_opcache_size; // length of co_opcache.
};
Copy after login
The code object PyCodeObject is used to store the compilation results, including bytecodes and constants, names, etc. involved in the code. Key fields include:
>>> result.co_consts
(3.14, <code object circle_area at 0x0000023D04D3F310, file "D:\myspace\code\pythonCode\mix\demo.py", line 3>, 'circle_area', <code object Person at 0x0000023D04D3F5D0, file "D:\myspace\code\pythonCode\mix\demo.py", line 6>, 'Person', None)
>>> person_code = result.co_consts[3]
>>> person_code
<code object Person at 0x0000023D04D3F5D0, file "D:\myspace\code\pythonCode\mix\demo.py", line 6>
>>> person_code.co_consts
('Person', <code object __init__ at 0x0000023D04D3F470, file "D:\myspace\code\pythonCode\mix\demo.py", line 7>, 'Person.__init__', <code object say at 0x0000023D04D3F520, file "D:\myspace\code\pythonCode\mix\demo.py", line 10>, 'Person.say', None)
The above is the detailed content of The execution process of a Python program includes converting source code into bytecode (i.e. compilation) and executing the bytecode. For more information, please follow other related articles on the PHP Chinese website!
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
VS Code can be used to write Python and provides many features that make it an ideal tool for developing Python applications. It allows users to: install Python extensions to get functions such as code completion, syntax highlighting, and debugging. Use the debugger to track code step by step, find and fix errors. Integrate Git for version control. Use code formatting tools to maintain code consistency. Use the Linting tool to spot potential problems ahead of time.
In VS Code, you can run the program in the terminal through the following steps: Prepare the code and open the integrated terminal to ensure that the code directory is consistent with the terminal working directory. Select the run command according to the programming language (such as Python's python your_file_name.py) to check whether it runs successfully and resolve errors. Use the debugger to improve debugging efficiency.
VS Code can run on Windows 8, but the experience may not be great. First make sure the system has been updated to the latest patch, then download the VS Code installation package that matches the system architecture and install it as prompted. After installation, be aware that some extensions may be incompatible with Windows 8 and need to look for alternative extensions or use newer Windows systems in a virtual machine. Install the necessary extensions to check whether they work properly. Although VS Code is feasible on Windows 8, it is recommended to upgrade to a newer Windows system for a better development experience and security.
VS Code extensions pose malicious risks, such as hiding malicious code, exploiting vulnerabilities, and masturbating as legitimate extensions. Methods to identify malicious extensions include: checking publishers, reading comments, checking code, and installing with caution. Security measures also include: security awareness, good habits, regular updates and antivirus software.
VS Code is the full name Visual Studio Code, which is a free and open source cross-platform code editor and development environment developed by Microsoft. It supports a wide range of programming languages and provides syntax highlighting, code automatic completion, code snippets and smart prompts to improve development efficiency. Through a rich extension ecosystem, users can add extensions to specific needs and languages, such as debuggers, code formatting tools, and Git integrations. VS Code also includes an intuitive debugger that helps quickly find and resolve bugs in your code.
Python excels in automation, scripting, and task management. 1) Automation: File backup is realized through standard libraries such as os and shutil. 2) Script writing: Use the psutil library to monitor system resources. 3) Task management: Use the schedule library to schedule tasks. Python's ease of use and rich library support makes it the preferred tool in these areas.
VS Code not only can run Python, but also provides powerful functions, including: automatically identifying Python files after installing Python extensions, providing functions such as code completion, syntax highlighting, and debugging. Relying on the installed Python environment, extensions act as bridge connection editing and Python environment. The debugging functions include setting breakpoints, step-by-step debugging, viewing variable values, and improving debugging efficiency. The integrated terminal supports running complex commands such as unit testing and package management. Supports extended configuration and enhances features such as code formatting, analysis and version control.
Yes, VS Code can run Python code. To run Python efficiently in VS Code, complete the following steps: Install the Python interpreter and configure environment variables. Install the Python extension in VS Code. Run Python code in VS Code's terminal via the command line. Use VS Code's debugging capabilities and code formatting to improve development efficiency. Adopt good programming habits and use performance analysis tools to optimize code performance.