Reference:
Https://www.cnblogs.com/bobo0609/p/6938012.html
Https://docs.python.org/2/tutorial/modules.html
1. Introduction :
In Python, a. py or. pyc file is called a module. That is, a file is considered a separate module, and a module can also be viewed as a file
. PY: The python source is stored
. PYC: Storing the Python interpreter's compiled bytecode for the source code
Python removes the filename from the. py/.pyc suffix as the module name, such as os.py, then its module name is OS
So suppose our current path has a os.py,python how do we know where it is and import it to use it?
This involves Python's module search path, which is searched in the following order:
<1> Current Path
<2>pythonpath variable Custom Path (Pythonpath is a system-defined environment variable, similar to path in CentOS)
<3> the path defined when you install Python
Some people wonder, how does Python know where my current path is?
This is because Python's program includes a top-level program file and other module files, the top-level file is equivalent to the application execution of the portal, similar to shell script, we must write the script to write absolute path or cut to the corresponding path to execute (this time the path is passed), Python is also the same
Example:
[[email protected ] python_learn]# pwd/root/python_learn[[email protected] python_learn]# cat getvalue.py#!/usr/local/anaconda2/bin/pythonx= ' Gx ' y= ' Gy ' z= ' Gz ' def f1 (x, Y, z): x= ' Ex ' z= ' Ez ' print x,y,z def f2 (x , y,z): x= ' Lx ' print x,y,z f2 (x, y, z) F1 (x, y, z) [[Email protected] python_ Learn]# cat index.py import getvalueprint x[[email protected] python_learn] # python index.py ex gy ezlx gy eztraceback (most recent call last): file "index.py", line 2, in <module> print xNameError: name ' x ' is not defined
Here index.py imported the GetValue module as a program entry, apparently Python found the GetValue module, because the program executes to print X, but why is there an "Ex Gy Ez" output?
This is because Python first imports the module (import or reload), the module file will immediately execute the top-level program code (not within the function of the code, such as variable x ' =GX ', function definition def F1, etc., as long as shelf write will be executed), The code in the body of the function is not executed until the function is called, so the F1 (x, y, z) function is called, the "Ex Gy ez" is printed, and F1 calls F2 itself, so the F2 function prints "Lx Gy ez"
So, since the module has been successfully imported, the X variable should have a definition, why does it prompt "name ' x ' is not defined"?
This is because: in order to avoid everyone's same programming habits caused by a variety of variable coverage (such as Zhang San and John Doe is assigned to write two different modules, Zhang San habit of using X in his variables, John Doe is also accustomed to this, then when two modules are imported, because the variable name is the same, there must be a value will be overwritten), So Python creates a new namespace with the module name, creating a variable in the new namespace when the module is imported. Simply put, when importing the x variable of the GetValue module, X is no longer treated as X, but is treated as a getvalue.x
Example: (next example)
[[email protected] python_learn]# cat index.py import getvalueprint getvalue.x[[email protected] python_learn]# python in dex.py Ex Gy ezlx Gy EZGX
As you can see, the print statement is now ready to be output.
So, what if I want to be able to import the GetValue module anytime, anywhere, without cutting to the specified path?
At this point, we're going to use the Sys.path variable.
Example:
in [2]: import sysin [3]: sys.pathout [3]: [', '/usr/local/anaconda2/bin ', '/usr/local/anaconda2/lib/python27.zip ', '/usr/local /anaconda2/lib/python2.7 ', '/usr/local/anaconda2/lib/python2.7/plat-linux2 ', '/usr/local/anaconda2/ Lib/python2.7/lib-tk ', '/usr/local/anaconda2/lib/python2.7/lib-old ', '/usr/local/anaconda2/lib/ Python2.7/lib-dynload ', '/usr/local/anaconda2/lib/python2.7/site-packages ', '/usr/local/anaconda2/ Lib/python2.7/site-packages/ipython/extensions ', '/root/.ipython ']in [4]: sys.path.insert ('/ root/python_learn/')---------------------------------------------------------------------------typeerror Traceback (most Recent call lAST) <ipython-input-4-b628fd39dcd4> in <module> ()----> 1 sys.path.insert ('/ root/python_learn/') Typeerror: insert () takes exactly 2 arguments (1 given) in [5]: help (List.insert) In [6]: sys.path.insert (, '/root/python_learn/') file "<ipython-input-6-c98c91c9451b>", line 1 sys.path.insert (, '/ root/python_learn/') ^syntaxerror: invalid syntaxin [7]: sys.path.insert (0, '/root /python_learn/') in [8]: sys.pathout[8]: ['/root/python_learn/', ', '/usr/local/ Anaconda2/bin ', '/usr/local/anaconda2/lib/python27.zip ', '/usr/local/anaconda2/lib/python2.7 ', '/usr/local/anaconda2/lib/python2.7/plat-linux2 ', '/usr/local/anaconda2/lib/python2.7/lib-tk ', '/usr /local/anaconda2/Lib/python2.7/lib-old ', '/usr/local/anaconda2/lib/python2.7/lib-dynload ', '/usr/local/anaconda2/lib/ Python2.7/site-packages ', '/usr/local/anaconda2/lib/python2.7/site-packages/ipython/extensions ', '/ Root/.ipython ']in [9]: import getvalueex gy ezlx gy ezin [10]: getvalue.xOut[10]: ' Gx '
Python looks for the module in the order of Sys.path, it is important to note that the Insert method requires two parameters, the first is the index, where 0 is used, the first place, the preference to find our own directory
If we import,python again and do not execute the top-level program code again, we simply reload the objects in memory
Example:
In []: import Getvaluein [+]: GetValue reload File "<ipython-input-30-7cba10969034>", line 1 GetValue Reload ^syntaxerror:invalid syntaxin []: Help (Reload) in [+]: Reload (getvalue) Ex Gy ezlx Gy ezout[32]: <mo Dule ' GetValue ' from '/root/python_learn/getvalue.pyc ' >
Now, the module load is no problem, but I think every time to knock the full module name GetValue, too annoying, there is no way?
I'm going to use the Import-as statement at this point.
Example:
in [[]: Import GetValue as gIn [+]: g.xout[34]: ' Gx '
Import xx as x: Will originally create a namespace named Getvlaue changed to G, so the call is simple, because it is modified so at this time GetValue this namespace does not exist, so can not use getvalue+ '. ' Get value
So if I'm more headstrong, I want to overwrite the variable x in my current environment?
This is the time to use the From-import statement.
Example:
in [+]: from GetValue import xIn [approx]: xout[36]: ' Gx '
The From-import statement will only load the corresponding property or method into the current namespace, so the other statements will not execute
So the Python import module is roughly divided into the following categories:
Import: Importing Directly
Import Module as Module_alias: alias for variable
From Module import attribute/method: Importing partial Properties/methods
Reload (Module): Re-import
Since as a module, it should have as a module of consciousness, an import on the blind execution will be clear-_-!!
Therefore, we should not let the module contain the statements that should not be executed, such as the function should not be called. But I think this module file sometimes as a top-level file execution, sometimes as a module is imported, then there is a way?
This time you can use the built-in attribute __name__.
Example:
[[email protected] python_learn]# cp Getvalue.py new.py[[email protected] python_learn]# vi new.py [[email protected] python_learn]# cat new.py #!/usr/local/anaconda2/bin/pythonx= ' Gx ' y= ' Gy ' z= ' Gz ' def f1 (x, Y, z): x= ' Ex ' z= ' Ez ' Print x,y,z def f2 (z/y): x= ' Lx ' Print x,y,z f2 (x, y,z) if __name__ == "__main__" : f1 (x, y, z) [[email protected] python_learn]# python new.py ex gy ezlx gy ez======================== ====================in [6]: import newin [7]: new.xout[7]: ' Gx ' In [8]: reload (new) out[8]: <module ' new ' from ' New.pyc ' >in [9]: new.__name__ out[9]: ' New '
Here the built-in variable __name__, if the program is the top-level file is "__main__", otherwise the module name
2.import working mechanism (excerpt from: https://www.cnblogs.com/bobo0609/p/6938012.html)
Import statement performs 3 steps when importing a specified module
1. Locate the module file: Search for the module file under the module search path
The program's home directory
Pythonpath Directory
Standard link Library Directory
2. Compile into bytecode: files are compiled when imported, so the. PYc bytecode files of the top-level files are discarded after internal use and only the files that are imported are left. pyc file
3. Execute the code of the module to create the object it defines: All statements in the module file are executed from beginning to the beginning, and any assignment to the variable name in this step produces the properties of the resulting module file
Note: The module does not perform the previous step only on the first import, and subsequent import operations are simply extracting the loaded module objects in memory, reload () can be used to reload the module
Package: Used to merge a set of modules into a directory, which is a package, and the directory name is the package name
A package is a hierarchical file directory structure that defines a Python application execution environment consisting of modules and sub-packages
Based on the package, Python can specify the module's import path when executing the module import pack1.pack2.mod1
There must be a __init__.py file within each package, __init__.py can contain Python code, but it is usually empty and is used only to play the role of package initialization, generating module namespaces for catalogs, and implementing from* behavior when using catalog Import
Python's modules