First, a simple example
def Add (A, b): return A + b
add_nums.py
import Fooa = [1, ' ' func () Foo.add ( 1, 2)
demo.py
Run Python demo.py
In Python3, a folder is automatically generated __pycache__ and the .pyc file is in this folder
Second, the principle behind
1. Compiling
Python will have a main module in the process, which includes if __name__ = = ' __main__ ' or a directly run PY file
Compile the user-defined module into the Pycodeobject object and load it into memory, save it as PYc file on disk after the compilation is finished
This Pycodeobject object contains the strings in the Python source code, the constant values, and the bytecode instructions generated by the syntax parsing.
2. How to generate PYC (Python bytecode bytecode file) file
1. The custom module will be generated automatically when running
2.python -m compileall file_path利用Python命令手动生成
3. Compile with the Py_compile package
Import py_compile >>> py_compile.compile ('abc.py')
3. How to decompile a bytecode file
PYC file is binary file, open after direct view is garbled, Python provides dis package
Common methods in Dis:
Dis.dis ([bytesource]) Bytesource can be a module, class, method, or Code object
Using DIS to process files
s = open ('demo.py'demo.py'exec ')import Disdis.dis (CO)
dis processing file
def MyFunc (alist): return len (alist)
>>> Dis.dis (myfunc) 2 0 Load_g Lobal 0 (len) 3 Load_fast 0 (alist) 6 call_function 1 9 return_value
- the line number, for the first instruction of the lines--------------------------corresponding source file Number, the first instruction in each line will display
- the current instruction, indicated As
--> ,-----------------------------------------current instruction-->
- a labelled instruction, indicated With
>> ,------- ---------------------------------tag Directive >>
- The address of the instruction,----------------------------- The address of the------------------------Directive
- The operation code name,--------------------------------------------------- --------Operation code Name
- operation parameters, and-----------------------------------------------------------operation parameters
- Interpretation of the parameters in parentheses.-------------------------------explanation of parameters in parentheses
link 32.12.3. Python bytecode instructions have the appropriate operation of the simple instructions you can refer to the specific
For specific information, please refer to: Blog of freshwater Blogs
The dis of Python source code analysis