Introduction to Python Standard Library series modules

Source: Internet
Author: User
The Python module encapsulates one or more functional code sets for reuse. a module can be a file or a directory, and the Directory form is called a package. Module classification built-in modules can be understood as that after you have installed the python environment, you can directly use im... the Python module encapsulates one or more functional code sets for reuse. the module can be FileIt can also be DirectoryDirectory is called Package.

Module category

Built-in modules

The built-in module can be understood to be used directly after you have installed the python environment.importThe imported module is the built-in module. the default module path is:C:\Python35\libYou can also obtain the path of the built-in module in the following ways:

# Import sys module> import sys # The last Directory is the path of the built-in module> for n in sys. path :... print (n )... c: \ Python35 \ lib \ site-packages \ pip-8.1.1-py3.5.eggC: \ Python35 \ python35.zipC: \ Python35 \ DLLsC: \ Python35 \ libC: \ Python35C: \ Python35 \ lib \ site-packages

Third-party module

Third-party modules are usually written by developers and then submitted to the official python library, so that we can download and install them. the default installation directory isC:\Python35\lib\site-packages,

Custom Module

Self-compiled modules

Module import method

Import a module as a whole

import sys

Import a specific variable or method from a module

from sys import path

Directly use the method name when callingpath

>>> path['', 'C:\\Python35\\lib\\site-packages\\pip-8.1.1-py3.5.egg', 'C:\\Python35\\python35.zip', 'C:\\Python35\\DLLs', 'C:\\Python35\\lib', 'C:\\Python35', 'C:\\Python35\\lib\\site-packages']

Alias the imported module or method

from sys import path as path_alias

Alias used for callingpath_alias

>>> path_alias['', 'C:\\Python35\\lib\\site-packages\\pip-8.1.1-py3.5.egg', 'C:\\Python35\\python35.zip', 'C:\\Python35\\DLLs', 'C:\\Python35\\lib', 'C:\\Python35', 'C:\\Python35\\lib\\site-packages']

Add the default environment variable, which is currently in effect

sys.path.append("PATH_NAME")

AvailableimpModulereloadMethod to re-load a module, for example, the following example:

$ cat simple.py #!/use/bin/env pythonprint('Hello, World!')spam = 1
>>> import simpleHello, World!>>> simple.spam1>>> simple.spam += 1>>> import simple>>> simple.spam2>>> import imp>>> imp.reload(simple)Hello, World!
 
  >>> simple.spam1
 
Module import sequence
  1. First, find the file with the same name as the import module in the current script Directory. If yes, import the file as a module (according to incomplete statistics, this is a pitfall, testreThe module is normal, but the testsysThe module is faulty)

  2. Find out whether there is a corresponding module name under the module path.

  3. If no module name is found, an error is returned.

How does import work?

The module performs the following three steps when being imported:

  1. Find the module file through environment variables;

  2. Compile it into a bytecode file. if there is a bytecode file, import the bytecode file;

  3. Execute the code in the module to create the defined object;

The preceding three steps are performed only when the module is imported for the first time when the program is running. If this module has been imported and then imported again, the above three steps will be skipped, and it will directly extract the loaded module objects in the memory. The imported Python modules are saved insys.modulesDictionary.

_ X and _ all __

All the variables in the module_None of them startfrom *Imported

$ cat simple.py #!/use/bin/env python_spam1 = 1spam2 = 1
>>> From simple import * >>> dir () # _ spam1 is not imported into ['_ builtins _', '_ doc __', '_ name _', '_ package _', 'spam2']

Opposite__all__The variables in the list will befrom *Imported, not in__all__The variables in the list are not imported.

$ cat simple.py#!/use/bin/env python__all__ = ['spam2']spam1 = 1spam2 = 1
>>> From simple import * >>> dir () # spam1 is not imported into ['_ builtins _', '_ doc __', '_ name _', '_ package _', 'spam2']
Notes

According to incomplete statistics, if the name of the imported module contains this file in the current directory, the file under the current directory will only be used as the module, as shown below:

Create a script file named scripts

[root@iZ28i253je0Z ~]# touch scripts.py

Content is

#! /Usr/bin/env python # _ * _ coding: UTF-8 _ * _ # import a module reimport re # output the matched string abcprint (re. match ('\ w +', "abc "). group ())

Execute scripts

[Root @ iZ28i253je0Z ~] # Python scripts. py # output the matching result abc.

Create.pyFile namedre.py

[root@iZ28i253je0Z ~]# touch re.py

Content is

#! /Usr/bin/env python # _ * _ coding: UTF-8 _ * _ # Output Content modusprint ("Hello Word ")

Execute againscripts.pyScript

[Root @ iZ28i253je0Z ~] # Python scripts. py # output Hello WordHello Word # and then report the error "no match" method Traceback (most recent call last): File "scripts. py", line 6, in
 
  
Print (re. match ('\ w +', "abc"). group () AttributeError: 'Module 'object has no attribute 'match'
 

Why? BecausepythonSetre.pyAs a modulereNow, let's continue:

Changescripts.pyThe file content is as follows:

[root@iZ28i253je0Z ~]# cat scripts.py #!/usr/bin/env python# _*_ coding:utf-8 _*_import re

re.pyThe file content remains unchanged, and then we are executing the scriptscripts.py

[root@iZ28i253je0Z ~]# python scripts.py Hello Word

See it. he willre.pyGet the code in the filescripts.pyFile Execution. this is a pitfall. do not step on it.

Import files in subdirectories of the current directory
[Root @ ansheng ~] # Tree. /. /├ ── modules │ ├ ── _ init __. py │ ── lib01.py │ └ ── lib02.py ── scripts. py1 directory, 4 files [root @ ansheng ~] # Cat scripts. py #! /Usr/bin/env python # import the lib01 module under the modules package from modules import lib01 # import the lib02 module under the modules package from modules import lib02 [root @ ansheng ~] # Cat modules/_ init _. py #! /Usr/bin/env python [root @ ansheng ~] # Cat modules/lib01.py #! /Usr/bin/env python # lib01.py file will output "Hello lib01" print ("Hello lib01") [root @ ansheng ~] # Cat modules/lib02.py #! /Usr/bin/env python # The lib02.py file will output "Hello lib02" print ("Hello lib02 ")

Execution result

[Root @ ansheng ~] # Python scripts. py # The modules/lib02.py and modules/lib01.py file content Hello lib01Hello lib02 will be executed

You must declare__init__.pyFile, even if the file is empty.

Original article link


The Python module encapsulates one or more functional code sets for reuse. the module can beFileIt can also beDirectoryDirectory is calledPackage.

Module category

Built-in modules

The built-in module can be understood to be used directly after you have installed the python environment.importThe imported module is the built-in module. the default module path is:C:\Python35\libYou can also obtain the path of the built-in module in the following ways:

# Import sys module> import sys # The last Directory is the path of the built-in module> for n in sys. path :... print (n )... c: \ Python35 \ lib \ site-packages \ pip-8.1.1-py3.5.eggC: \ Python35 \ python35.zipC: \ Python35 \ DLLsC: \ Python35 \ libC: \ Python35C: \ Python35 \ lib \ site-packages

Third-party module

Third-party modules are usually written by developers and then submitted to the official python library, so that we can download and install them. the default installation directory isC:\Python35\lib\site-packages,

Custom Module

Self-compiled modules

Module import method

Import a module as a whole

import sys

Import a specific variable or method from a module

from sys import path

Directly use the method name when callingpath

>>> path['', 'C:\\Python35\\lib\\site-packages\\pip-8.1.1-py3.5.egg', 'C:\\Python35\\python35.zip', 'C:\\Python35\\DLLs', 'C:\\Python35\\lib', 'C:\\Python35', 'C:\\Python35\\lib\\site-packages']

Alias the imported module or method

from sys import path as path_alias

Alias used for callingpath_alias

>>> path_alias['', 'C:\\Python35\\lib\\site-packages\\pip-8.1.1-py3.5.egg', 'C:\\Python35\\python35.zip', 'C:\\Python35\\DLLs', 'C:\\Python35\\lib', 'C:\\Python35', 'C:\\Python35\\lib\\site-packages']

Add the default environment variable, which is currently in effect

sys.path.append("PATH_NAME")

AvailableimpModulereloadMethod to re-load a module, for example, the following example:

$ cat simple.py #!/use/bin/env pythonprint('Hello, World!')spam = 1
>>> import simpleHello, World!>>> simple.spam1>>> simple.spam += 1>>> import simple>>> simple.spam2>>> import imp>>> imp.reload(simple)Hello, World!
 
  >>> simple.spam1
 
Module import sequence
  1. First, find the file with the same name as the import module in the current script Directory. If yes, import the file as a module (according to incomplete statistics, this is a pitfall, testreThe module is normal, but the testsysThe module is faulty)

  2. Find out whether there is a corresponding module name under the module path.

  3. If no module name is found, an error is returned.

How does import work?

The module performs the following three steps when being imported:

  1. Find the module file through environment variables;

  2. Compile it into a bytecode file. if there is a bytecode file, import the bytecode file;

  3. Execute the code in the module to create the defined object;

The preceding three steps are performed only when the module is imported for the first time when the program is running. If this module has been imported and then imported again, the above three steps will be skipped, and it will directly extract the loaded module objects in the memory. The imported Python modules are saved insys.modulesDictionary.

_ X and _ all __

All the variables in the module_None of them startfrom *Imported

$ cat simple.py #!/use/bin/env python_spam1 = 1spam2 = 1
>>> From simple import * >>> dir () # _ spam1 is not imported into ['_ builtins _', '_ doc __', '_ name _', '_ package _', 'spam2']

Opposite__all__The variables in the list will befrom *Imported, not in__all__The variables in the list are not imported.

$ cat simple.py#!/use/bin/env python__all__ = ['spam2']spam1 = 1spam2 = 1
>>> From simple import * >>> dir () # spam1 is not imported into ['_ builtins _', '_ doc __', '_ name _', '_ package _', 'spam2']
Notes

According to incomplete statistics, if the name of the imported module contains this file in the current directory, the file under the current directory will only be used as the module, as shown below:

Create a script file named scripts

[root@iZ28i253je0Z ~]# touch scripts.py

Content is

#! /Usr/bin/env python # _ * _ coding: UTF-8 _ * _ # import a module reimport re # output the matched string abcprint (re. match ('\ w +', "abc "). group ())

Execute scripts

[Root @ iZ28i253je0Z ~] # Python scripts. py # output the matching result abc.

Create.pyFile namedre.py

[root@iZ28i253je0Z ~]# touch re.py

Content is

#! /Usr/bin/env python # _ * _ coding: UTF-8 _ * _ # Output Content modusprint ("Hello Word ")

Execute againscripts.pyScript

[Root @ iZ28i253je0Z ~] # Python scripts. py # output Hello WordHello Word # and then report the error "no match" method Traceback (most recent call last): File "scripts. py", line 6, in
 
  
Print (re. match ('\ w +', "abc"). group () AttributeError: 'Module 'object has no attribute 'match'
 

Why? BecausepythonSetre.pyAs a modulereNow, let's continue:

Changescripts.pyThe file content is as follows:

[root@iZ28i253je0Z ~]# cat scripts.py #!/usr/bin/env python# _*_ coding:utf-8 _*_import re

re.pyThe file content remains unchanged, and then we are executing the scriptscripts.py

[root@iZ28i253je0Z ~]# python scripts.py Hello Word

See it. he willre.pyGet the code in the filescripts.pyFile Execution. this is a pitfall. do not step on it.

Import files in subdirectories of the current directory
[Root @ ansheng ~] # Tree. /. /├ ── modules │ ├ ── _ init __. py │ ── lib01.py │ └ ── lib02.py ── scripts. py1 directory, 4 files [root @ ansheng ~] # Cat scripts. py #! /Usr/bin/env python # import the lib01 module under the modules package from modules import lib01 # import the lib02 module under the modules package from modules import lib02 [root @ ansheng ~] # Cat modules/_ init _. py #! /Usr/bin/env python [root @ ansheng ~] # Cat modules/lib01.py #! /Usr/bin/env python # lib01.py file will output "Hello lib01" print ("Hello lib01") [root @ ansheng ~] # Cat modules/lib02.py #! /Usr/bin/env python # The lib02.py file will output "Hello lib02" print ("Hello lib02 ")

Execution result

[Root @ ansheng ~] # Python scripts. py # The modules/lib02.py and modules/lib01.py file content Hello lib01Hello lib02 will be executed

You must declare__init__.pyFile, even if the file is empty.

For more articles about The Python Standard Library series, refer to the PHP Chinese network!

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.