In the previous chapters, we basically use python Interpreter to program , If you Python The interpreter exits and then enters , Then all the methods and variables you define disappear .
So Python Provides a way , Put these definitions in a file , Use for some scripts or interactive interpreter instances , This file is called a module .
A module is a file that contains all the functions and variables you define , Its suffix is .py. Modules can be introduced by other programs , To use functions in the module . This is also used python Standard library method .
Here is a use python Examples of modules in the standard library .
#!/usr/bin/python3 # file name : using_sys.py import sys print(' The command line parameters are as follows :') for i in sys.argv: print(i) print('\n\nPython Path is :', sys.path, '\n')
The results are shown below :
$ python using_sys.py Parameters 1 Parameters 2 The command line parameters are as follows : using_sys.py Parameters 1 Parameters 2 Python Path is : ['/root', '/usr/lib/python3.4', '/usr/lib/python3.4/plat-x86_64-linux-gnu', '/usr/lib/python3.4/lib-dynload', '/usr/local/lib/python3.4/dist-packages', '/usr/lib/python3/dist-packages']
Want to use Python Source file , Just execute it in another source file import sentence , The grammar is as follows :
import module1[, module2[,... moduleN]
When the interpreter encounters import sentence , If the module is in the current search path it will be imported .
The search path is a list of all directories that the interpreter will search first . If you want to import modules support, You need to put the command at the top of the script :
#!/usr/bin/python3 # Filename: support.py def print_func( par ): print ("Hello : ", par) return
test.py introduce support modular :
#!/usr/bin/python3 # Filename: test.py # The import module import support # Now you can call the functions contained in the module support.print_func("Runoob")
The output of the above example :
$ python3 test.py Hello : Runoob
A module can only be imported once , No matter how many times you execute import. This prevents the import module from being executed over and over again .
When we use import At the time of statement ,Python How does the interpreter find the corresponding file ?
This involves Python Search path for , The search path is made up of a series of directory names ,Python The interpreter looks for the introduced modules from these directories in turn .
It looks like an environment variable , in fact , You can also define the search path by defining environment variables .
The search path is in Python When compiling or installing , Installing new libraries should also change . The search path is stored in sys Module path Variable , Do a simple experiment , In the interactive interpreter , Enter the following code :
>>> import sys >>> sys.path ['', '/usr/lib/python3.4', '/usr/lib/python3.4/plat-x86_64-linux-gnu', '/usr/lib/python3.4/lib-dynload', '/usr/local/lib/python3.4/dist-packages', '/usr/lib/python3/dist-packages'] >>>
sys.path The output is a list , The first one is an empty string '', Represents the current directory ( If it's printed from a script , You can see more clearly which directory it is ), That is, we implement python The directory of the interpreter ( For scripts, it's the directory where the scripts are running ).
Therefore, if a file with the same name as the module to be imported exists in the current directory like me , The module to be introduced will be shielded .
Understand the concept of search path , You can modify... In the script sys.path To introduce some modules that are not in the search path .
Now? , In the current directory of the interpreter or sys.path Create a directory in the fibo.py The file of , The code is as follows :
# Fibonacci (fibonacci) Sequence module def fib(n): # Define the n The Fibonacci sequence of a, b = 0, 1 while b < n: print(b, end=' ') a, b = b, a+b print() def fib2(n): # Back to n The Fibonacci sequence of result = [] a, b = 0, 1 while b < n: result.append(b) a, b = b, a+b return result
Then enter Python Interpreter , Use the following command to import this module :
>>> import fibo
This does not directly define fibo The function name in is written into the current symbol table , Just put the module fibo Your name is written there .
You can use the module name to access the function :
>>>fibo.fib(1000) 1 1 2 3 5 8 13 21 34 55 89 144 233 377 610 987 >>> fibo.fib2(100) [1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89] >>> fibo.__name__ 'fibo'
If you're going to use a function a lot , You can assign it to a local name :
>>> fib = fibo.fib >>> fib(500) 1 1 2 3 5 8 13 21 34 55 89 144 233 377
Python Of from Statement allows you to import a specified part from a module into the current namespace , The grammar is as follows :
from modname import name1[, name2[, ... nameN]]
for example , To import a module fibo Of fib function , Use the following statement :
>>> from fibo import fib, fib2 >>> fib(500) 1 1 2 3 5 8 13 21 34 55 89 144 233 377
This statement will not take the whole fibo Modules are imported into the current namespace , It will only fibo Inside fib Function is introduced .
It is also possible to import all the contents of a module into the current namespace , Just use the following statement :
from modname import *
This provides a simple way to import all the projects in a module . However, such a declaration should not be used too much .
Module except method definition , You can also include executable code . This code is usually used to initialize the module . The code is only executed when it is first imported .
Each module has its own symbol table , Within the module, it is used as a global symbol table for all functions .
therefore , The author of the module can be assured to use these global variables within the module , You don't have to worry about confusing other users' global variables .
On the other hand , When you do know what you're doing , You can also pass modname.itemname This representation is used to access functions within a module .
Modules can be imported into other modules . In a module ( Or scripts , Or somewhere else ) The first use of import To import a module , Of course, it's just a convention , It's not mandatory . The name of the imported module will be put into the symbol table of the module in the current operation .
There is another way to import , have access to import Directly into the module ( function , Variable ) Import the name into the current operation module . such as :
>>> from fibo import fib, fib2 >>> fib(500) 1 1 2 3 5 8 13 21 34 55 89 144 233 377
This import method does not put the name of the imported module in the current character table ( So in this case ,fibo This name is undefined ).
There is another way , You can put all the components in the module at one time ( function , Variable ) All names are imported into the character table of the current module :
>>> from fibo import * >>> fib(500) 1 1 2 3 5 8 13 21 34 55 89 144 233 377
This will import all the names , But those with a single underline (_) The first name is not in this case . In most cases , Python Programmers don't use this method , Because the names of other sources introduced , It's likely to cover the existing definition .
When a module is first introduced by another program , Its main program will run . If we want to introduce modules , A block in a module does not execute , We can use __name__ Property to make the block execute only when the module itself is running .
#!/usr/bin/python3 # Filename: using_name.py if __name__ == '__main__': print(' The program itself is running ') else: print(' I come from the first mock exam ')
The operation output is as follows :
$ python using_name.py The program itself is running
$ python >>> import using_name I come from the first mock exam >>>
explain : Each module has one __name__ attribute , When the value is '__main__' when , Indicates that the module itself is running , Otherwise it's introduced .
explain :__name__ And __main__ The bottom is double underline , _ _ That's how you get rid of the space in the middle .
Built in functions dir() You can find all the names defined within the module . Return as a list of strings :
>>> import fibo, sys >>> dir(fibo) ['__name__', 'fib', 'fib2'] >>> dir(sys) ['__displayhook__', '__doc__', '__excepthook__', '__loader__', '__name__', '__package__', '__stderr__', '__stdin__', '__stdout__', '_clear_type_cache', '_current_frames', '_debugmallocstats', '_getframe', '_home', '_mercurial', '_xoptions', 'abiflags', 'api_version', 'argv', 'base_exec_prefix', 'base_prefix', 'builtin_module_names', 'byteorder', 'call_tracing', 'callstats', 'copyright', 'displayhook', 'dont_write_bytecode', 'exc_info', 'excepthook', 'exec_prefix', 'executable', 'exit', 'flags', 'float_info', 'float_repr_style', 'getcheckinterval', 'getdefaultencoding', 'getdlopenflags', 'getfilesystemencoding', 'getobjects', 'getprofile', 'getrecursionlimit', 'getrefcount', 'getsizeof', 'getswitchinterval', 'gettotalrefcount', 'gettrace', 'hash_info', 'hexversion', 'implementation', 'int_info', 'intern', 'maxsize', 'maxunicode', 'meta_path', 'modules', 'path', 'path_hooks', 'path_importer_cache', 'platform', 'prefix', 'ps1', 'setcheckinterval', 'setdlopenflags', 'setprofile', 'setrecursionlimit', 'setswitchinterval', 'settrace', 'stderr', 'stdin', 'stdout', 'thread_info', 'version', 'version_info', 'warnoptions']
If there is no given parameter , that dir() The function lists all the names currently defined :
>>> a = [1, 2, 3, 4, 5] >>> import fibo >>> fib = fibo.fib >>> dir() # Get a list of attributes defined in the current module ['__builtins__', '__name__', 'a', 'fib', 'fibo', 'sys'] >>> a = 5 # Create a new variable 'a' >>> dir() ['__builtins__', '__doc__', '__name__', 'a', 'sys'] >>> >>> del a # Delete variable name a >>> >>> dir() ['__builtins__', '__doc__', '__name__', 'sys'] >>>
Python It comes with some standard module Libraries , stay Python The library reference document will cover ( It's the back of it " Kurt's documents ").
Some modules are built directly into the parser , These are not built-in features of some languages , But he can use it very efficiently , Even system level calls are OK .
These components will be configured in different forms according to different operating systems , such as winreg Only this module will be provided Windows System .
It should be noted that there is a special module sys , It's built into every Python The parser . Variable sys.ps1 and sys.ps2 Defines the string corresponding to the main prompt and secondary prompt :
>>> import sys >>> sys.ps1 '>>> ' >>> sys.ps2 '... ' >>> sys.ps1 = 'C> ' C> print('Runoob!') Runoob! C>
Package is a kind of management Python The form of the module namespace , use " Point module name ".
For example, the name of a module is A.B, So he means a bag A Sub modules in B .
It's like using modules , You don't have to worry about the same global variables between different modules , In the form of point module name, there is no need to worry about the duplicate names of modules between different libraries .
In this way, different authors can provide NumPy modular , Or is it Python Graphics library .
Suppose you want to design a unified processing module for sound files and data ( Or call it a " package ").
There are many different audio file formats available ( It's basically distinguished by suffixes , for example : .wav,:file:.aiff,:file:.au,), So you need to have a growing set of modules , Used to convert between different formats .
And for the audio data , There are many different operations ( Like mixing , Add echo , Add equalizer function , Create artificial stereo effects ), So you also need a set of modules that can't be written to handle these operations .
Here is a possible package structure ( In a hierarchical file system ):
sound/ Top package __init__.py initialization sound package formats/ File format conversion package __init__.py wavread.py wavwrite.py aiffread.py aiffwrite.py auread.py auwrite.py ... effects/ Package effect __init__.py echo.py surround.py reverse.py ... filters/ filters subpackage __init__.py equalizer.py vocoder.py karaoke.py ...
When importing a package ,Python Will be based on sys.path To find the subdirectories contained in this package .
The directory contains only one called __init__.py Is a package , Mainly to avoid some vulgar names ( For example is called string) Carelessly affect the effective module in the search path .
In the simplest case , Put an empty one :file:__init__.py That's all right. . Of course, this file can also contain some initialization code or ( It will be introduced later ) __all__ Variable assignment .
Users can import only one specific module in a package at a time , such as :
import sound.effects.echo
This will import sub modules :sound.effects.echo. He must use his full name to access :
sound.effects.echo.echofilter(input, output, delay=0.7, atten=4)
Another way to import sub modules is :
from sound.effects import echo
This will also import sub modules : echo, And he doesn't need those long prefixes , So he can use :
echo.echofilter(input, output, delay=0.7, atten=4)
Another change is to import a function or variable directly :
from sound.effects.echo import echofilter
alike , This method will import sub modules : echo, And you can use his echofilter() function :
echofilter(input, output, delay=0.7, atten=4)
Pay attention when using from package import item In this form , Corresponding item It can be a sub module in the package ( subpackage ), Or any other name in the package , Like functions , Class or variable .
import Grammar will first put item As a package definition name , If not , Then try to import according to a module . If you haven't found it yet , Throw a :exc:ImportError abnormal .
conversely , If you use the form import item.subitem.subsubitem This form of import , Except for the last term , All have to be bags , The last item can be a module or a package , No, but class , The name of a function or variable .
If we use from sound.effects import * What will happen ?
Python Will enter the file system , Find all the sub modules in this package , Then import them one by one .
But this method is in Windows The work on the platform is not very good , because Windows Is a case insensitive system .
stay Windows On the platform , We can't be sure that one is called ECHO.py The file imported as a module is echo still Echo, Or is it ECHO.
To solve this problem , We just need to provide an accurate package index .
The import statement follows the following rules : If the package definition file __init__.py There is one called __all__ List variables of , So in use from package import * All the names in this list will be imported as package contents .
As the author of the package , Don't forget to guarantee after updating the package __all__ Also updated .
The following examples are in file:sounds/effects/__init__.py Contains the following code :
__all__ = ["echo", "surround", "reverse"]
This means that when you use from sound.effects import * In this way , You can only import the three sub modules in the package .
If __all__ There's really no definition , So use from sound.effects import * When it comes to this grammar , The package will not be imported sound.effects Any sub module in . He just put the bag sound.effects And all the content defined in it ( It's possible to run __init__.py Initialization code defined in ).
This will turn __init__.py Import all the names defined inside . And it will not destroy all the explicitly specified modules we imported before this sentence . Take a look at this code :
import sound.effects.echo import sound.effects.surround from sound.effects import *
In this case , In execution from...import front , package sound.effects Medium echo and surround Modules are imported into the current namespace .( Of course, if defined __all__ Even more no problem )
Usually we do not advocate the use of * This method is used to import modules , Because this approach often leads to a reduction in the readability of the code . But it really saves a lot of keystrokes , And some modules are designed to be imported only through specific methods .
remember , Use from Package import specific_submodule This method can never be wrong . in fact , This is also the recommended method . Unless the sub module you want to import may have the same name as the sub module of other packages .
If the package is a sub package in the structure ( For example, in this example, for the package sound Come on ), And you want to import the brother package ( Packages of the same level ) You have to use the import absolute path to import . such as , If the module sound.filters.vocoder To use a package sound.effects Module in echo, You have to write from sound.effects import echo.
from . import echo from .. import formats from ..filters import equalizer
Whether implicit or explicit, the relative Import starts from the current module . The name of the main module is always "__main__", One Python The main module of the application , You should always use absolute path references .
The package also provides an additional attribute __path__. This is a list of directories , Each directory contained in it has a service for this package __init__.py, You have to be in other __init__.py Defined before execution . You can modify this variable , Used to affect the modules and sub packages contained in the package .
This feature is not commonly used , It is generally used to expand the modules in the package .