Python module
Python code can be stored in a file, for some scripts or interactive interpreter instances, this file is called a module.
A module is a file that contains all of the functions and variables that you define, followed by a. PY module that can be introduced by other programs to use functions such as functions in the module. This is also the way to use the Python standard library. Here is an example of using a module in the Python standard library
import sysprint(‘命令行参数如下:‘)forin sys.argv: print(i)print(‘/n/nThe PYTHONPATH is‘‘/n‘)
Description
①import SYS introduces the sys.py module in the Python standard library, which is a method of introducing a module.
②SYS.ARGV is a list that contains command-line arguments
③sys.path contains a list of paths that the Python interpreter automatically finds for the required modules.
The search path is determined by the time the Python is compiled or installed, and the installation of the new library should also be modified. The search path is stored in the PATH variable in the SYS module, such as
>>> sys.path[‘‘, ‘E:\\python33\\Lib\\idlelib‘, ‘C:\\Windows\\system32\\python33.zip‘, ‘E:\\python33\\DLLs‘, ‘E:\\python33\\lib‘, ‘E:\\python33‘, ‘E:\\python33\\lib\\site-packages‘]
The Sys.path output is a list where the first item is an empty string representing the current directory. You can modify the Sys.path in the script to introduce some modules that are not in the search path. Such as
#fibo.py文件def fib(n): # write Fibonacci series up to n 01 while b < n: print(b, end=‘ ‘) a, b = b, a+b print()
Then import in the Python interpreter
Import Fibo
Doing so does not write the function name directly defined in Fibo to the current symbol table, just writes the name of the module Fibo there. You can use the module name to access the function.
Such as
FIBO.FIB (1000)
1 1 2 3 5 8 13 21 34 5 89 144 233 377 610 987
Fibo. _name_
' Fibo '
In-depth modules
Modules can include executable code in addition to the method definition. This code is typically used to initialize the module. The code will be executed only if it is imported for the first time.
Each module has its own separate symbol table, which is used within the module as a global symbol table for all functions. Therefore, the author of the module can rest assured that these global variables are used inside the module without worrying about spending other users ' global variables.
On the other side, when you do know what you're doing, you can also access the functions within the module in a modname.itemname way. Modules can be imported into other modules. Importing a module in front of a module (or script or somewhere else) uses import, which is, of course, a convention, not a mandatory one. The name of the module being imported is placed in the symbol table of the module of the current operation.
There is also an import method that can import the name of a module (function, variable) directly into the current operation module using import.
From Fibo import fib
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 module being imported into the current character table (so in this case Fibo the name is undefined)
There is also a way to import all (function variable) names from the module into the character list of the current module at once
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 in.
_name_Property
When a module is introduced for the first time by another program, its main program will run. If we want a block in the module to be introduced, we can use the _name_ property to make the block execute only when the module itself is running.
Each module has a _name_ property that, when its value is '_main_', indicates that the module itself is running, otherwise it is introduced.
#hello.pyif‘__main__‘: print("程序自身在运行")else: print("我来自另一模块")python hello.py>>>程序自身在运行import hello>>>我来自另一模块
Dir () function
The built-in function dir () can find all the names defined within the module. Returned as a list of strings:
Import Sysdir(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 Dir () does not have a given parameter, then the DIR () function lists all the names currently defined.
Standard modules
python itself carries some standard library of modules . Some modules are built directly into the parser, which is not a feature built into the language, but can be used efficiently, even system-level calls.
These components are configured differently depending on the operating system, such as the WinReg module, which is only available to Windows systems.
It should be noted that there is a special module SYS, which is built into each Python parser , and the variables Sys.ps1 and SYS.PS2 define the string for the main prompt and the Vice-prompt.
>>> import sys>>> sys.ps1‘>>> ‘>>> sys.ps2‘... ‘>>> ‘C> ‘C> print(‘Yuck!‘)Yuck!C>
Package
A package is a form of managing a Python module namespace, with a "point module name".
For example, the name of a module is A.B then he represents a sub-module B in Package A.
As a possible package structure (in a layered file system)
sound/top-level package __init__.py Initialize The Sound package formats/subpackage for file fo Rmat conversions __init__.py wavread.py wavwrite.py aiffread.py aiffwrite.py auread.py auwrite.py ... Effects/subpackage for sound effects __init__.py echo.py surround.py reverse.py ... Filters/subpackage for filters __init__.py E qualizer.py vocoder.py karaoke.py ...
When importing a package, Python looks for subdirectories contained in the package based on the directories in the Sys.path.
Only files that contain a file called _init_. Py are considered to be a package, primarily to avoid the misuse of names (such as String) that inadvertently affects valid modules in the path.
Users can import only a specific module within a package at a time, such as
Import Sound.effects.echo
Access must be accessed using the full name:
Sound.effects.echo.echofilter (input,output,delay=0.7,atten=4)
Another way to import submodules is to:
From sound.effects import Echo
Such an import can be used like this:
Echo.echofilter (input,output,delay=0.7,atten=4)
Another change is to directly import a function or variable:
From Sound.effects.echo import Echofilter
This allows the import to be used directly
Echofliter (input,output,delay=0.7,atten=4)
Note: When you use the From package import item, the corresponding item can be either a sub-module (a child package) or another name defined within the package, such as a function, class, or variable .
Import syntax starts with item as the name of a package definition, and if not found, attempts to import by a module and throws an exception if it is not found.
If you use import item.subitem.subsubitem this form, except for the last item, it must be a package, and the last item can be either a module or a package, but it can not be a class, function, or variable.
Import from a package
The import statement follows the following rules: If the package definition file _init_. PY has a list variable called _all_ , then all the names in this list are imported as package content when using the From packages import *.
So, as the author of the package, don't forget to make sure that _all_ is updated after the package is updated.
For example, the following code is included in the _init_. PY:
_all_ = ["echo", "surround", "reverse"]
This means that when using the From sound.effects import * This usage, you will only import these three submodules in the package.
If _all_ does not have a definition, then when using the syntax of the From sound.effects Import *, the package is "not" imported: any submodule in the mod:sound.effects. He just imports the package mod:sound.effects and everything that's inside it. (May run: initialization code defined in file:_init_. Py)
This will import all the names defined in the file:_init_. Py, and he will not destroy all the explicitly specified modules that we imported before this sentence
Such as:
import sound.effects.echoimport sound.effects.surroundfrom sound.effects import *
Here, before the from import is executed, the Echo and surround modules in the package: Mod:sound.effects are imported into the current namespace. (Of course, if the definition of _all_ is even more no problem)
Remember that using the From package import Specific_submodule This method is never wrong. In fact, this is also the recommended method.
"Python" python module