pyhton in __pycache__ folder

the reason

We prepared a project with python, but after the first run, find the root of the project swells into a __pycache__folder, which is found in various folders and file of the same name py to  .cpython-35.pycthe end of the file.

The calling module

Python when import module, the module will be actually executed again introduced, as follows:
look at the module is called the test.py:

1 def funny():
2 print("有趣")
3 
4 funny()

Look at the main program main.py:

. 1  Import Test
 2  
. 3  Print ( "Hello " )

The results are:

1 interesting 
2 Hello

Then how can simply call without executing the code module is invoked it? To be called the module code is not executed, the variable __name__ premise must know what it means, in short, if you do not involve imported modules, then __ value name__ is __main__, if and when this module is imported quoted, then the value is the file name __name__ within this module (without .py) , as follows test_1.py:

1  DEF Funny ():
 2  Print ( "interesting " )
 3  
4 Funny ()
5 Print ( __name__ ) # does not involve calling

test_1.py Implementation of the results:

1 interesting 
2 __main__

If test_1 introduced quoted, such test_2:

. 1  Import TEST_1
 2  
. 3  Print ( "Hello " )

test_2x operating results as follows:

1 interesting 
2 TEST_1 3 Hello

If the top said to understand, then we are in a module to be called in, together with executable code before such a judgment, if __name__ == '__main__' :, code module to be called will not be executed !

The basic operating mechanism python

Probably first look at the basic operating mechanism python. Python compiled into binary code does not need to run time, run the program directly from the source, is simple, Python interpreter converts the source code into byte code, and then to execute bytecodes by an interpreter.

Specific work interpreter:
1, to complete the module loading and linking;
2, the source code is compiled into PyCodeObject object (i.e., byte code), a write memory for CPU to read;
3, read from the memory and executing , after the end of PyCodeObject written back to the hard disk among which is copied to .pyc or .pyo file to save the bytecode file in the current directory for all scripts.

If after executing the script again, it first checks whether the local [the above] and [bytecode file modification time whether the byte code file after its source file], is directly executed, otherwise repeat the above steps.

Meaning __pycache__ folder

Because for the first time when the execution of the code, Python interpreter has been compiled to byte code on __pycache__ folder, so that later run again, and if the module is invoked did not change, then skip this step compilation , go directly to __pycache__ folder to run the relevant * .pyc file, greatly reducing the preparation time before operation of the project .

Guess you like

Origin www.cnblogs.com/funnything/p/11009852.html