1-15 Python module

In the previous sections we are on the script with the python interpreter program, if you withdraw from re-entering the Python interpreter, then all the methods and variables you define it disappeared.

To this end Python provides a way to put these definitions stored in a file, for a number of scripts or interactive interpreter instance, this file is called a module.

Module is a file that contains all the functions and variables that you have defined, its name suffix .py. It may be introduced into another program module, the function or the like to use the function module. This is also the use of python standard library.

The following is an example of python standard library modules used.

#!/usr/bin/python3
# 文件名: using_sys.py
 
import sys
 
print('命令行参数如下:')
for i in sys.argv:
   print(i)
 
print('\n\nPython 路径为:', sys.path, '\n')

Execution results are as follows:

$ python using_sys.py 参数1 参数2
命令行参数如下:
using_sys.py
参数1
参数2


Python 路径为: ['/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'] 
  • 1, import sys introduced sys.py python standard library module; This is a method of introducing the module.
  • 2, sys.argv is a list of command line switches are included.
  • 3, sys.path Python interpreter contains a list of paths required to automatically find the module.

The import statement

Want to use Python source file, simply perform another import statement in the source file, the syntax is as follows:

import module1[, module2[,... moduleN]

When the interpreter encounters the import statement, if the module will be imported in the current search path.

Search path is a list of all directories that an interpreter will carry out a search . As you want to import module support, you need to command at the top of the script:

support.py file code

#!/usr/bin/python3
# Filename: support.py
 
def print_func( par ):
    print ("Hello : ", par)
    return

test.py introduction support module:

test.py file code

#!/usr/bin/python3
# Filename: test.py
 
# 导入模块
import support
 
# 现在可以调用模块里包含的函数了
support.print_func("Runoob")

Examples of the above output:

$ python3 test.py 
Hello :  Runoob

A module will only be imported once, no matter how many times you perform the import. This prevents the module being introduced executed over and over again.

When we use the import statement, Python interpreter is how to find the corresponding file it?

This involves the Python search path, the search path is composed of a series of directory names, Python interpreter will turn from these directories to search for modules introduced.

It looks like an environment variable, in fact, can also be determined by defining the search path environment variable manner.

Python compiler search path is determined when installing or install new library should also be modified. The search paths are stored in the variable path sys module , do a simple experiment, in an 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 output is a list, the first of the empty string '', represents the current directory (if the print out from a script, it may be more clearly seen which directory), i.e. we execute python interpreter directory ( for script, then run the script directory is located ).

So if, like me exist in the current directory with the same name as the file to be introduced into the module, the module will be introduced masked.

Understand the concept of the search path, you can modify sys.path in the script to introduce some not in the search path module.

Now, in the current directory or a directory in sys.path interpreter inside to create a fibo.py file , the code is as follows:

# 斐波那契(fibonacci)数列模块
 
def fib(n):    # 定义到 n 的斐波那契数列
    a, b = 0, 1
    while b < n:
        print(b, end=' ')
        a, b = b, a+b
    print()
 
def fib2(n): # 返回到 n 的斐波那契数列
    result = []
    a, b = 0, 1
    while b < n:
        result.append(b)
        a, b = b, a+b
    return result

Python interpreter then enters, using the following command to import the module:

>>> import fibo

This does not directly define the function name in fibo is written into the current symbol table, but the module name fibo wrote there.

You can use the module name to access functions:

>>>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 intend to use a function often 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

 


from ... import statement

Python's from statement lets you import a specified portion of the current namespace from the module, the syntax is as follows:

from modname import name1[, name2[, ... nameN]]

For example, to import function module fibo of fib, 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 is not the whole fibo module into the current namespace, it will only fibo function introduced in the fib come.

 


from ... import * statement

All the contents of a module are all imported into the current namespace is also possible, simply use the following statement:

from modname import *

This provides an easy way to import all items in a module. However, this statement should not be too much to use.


Depth module

The method defined in addition to the module, may further include executable code. These codes are generally used to initialize the module. This code will only be executed when it is first imported.

Each module has its own independent symbol table is used for all global symbol table as a function inside the module.

Therefore, the author of the module can safely use these global variables in the module without worrying about the other user's global variables out flowers.

From another aspect, when you really know what you're doing, you can also access the functions in the module through such representation modname.itemname.

Module can import other modules. In a module (or script, or elsewhere) in the front to use import to import a module, of course, this is just a convention, rather than mandatory. The name of the module to be introduced into the symbol table module is currently operating in.

Another method of introduction, may be used to directly import the module name (functions, variables) into the current operating 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 method of introduction is not the name of the module to be introduced in the current character table (so that even in this case, fibo name is not defined).

Another method which may be disposable to all the modules (functions, variables) are introduced into the character table names 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 are coming, but those names that begin with a single underscore (_) not in this case. In most cases, Python programmers do not use this method because names introduced from other sources, is likely to cover the existing definition.


__name__ property

When a module is first introduced into another program which runs the main program. If we want when the module is introduced, a block module is not performed, we can attribute to __name__ The block only executed in the runtime module itself.

#!/usr/bin/python3
# Filename: using_name.py

if __name__ == '__main__':
   print('程序自身在运行')
else:
   print('我来自另一模块')

Run the following output:

$ python using_name.py
程序自身在运行
$ python
>>> import using_name
我来自另一模块
>>>

Description:  Each module has a __name__ property, when its value is '__main__', it indicates that the module itself is running or is being introduced.

Description: __name__  and  __main__  under a double underscore, _ _ is removed in the middle of the space.


dir () function

Built-in function dir () can find all the names defined in the module. It returned 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 no argument is given, then the dir () function will set out the names of all currently defined:

>>> a = [1, 2, 3, 4, 5]
>>> import fibo
>>> fib = fibo.fib
>>> dir() # 得到一个当前模块中定义的属性列表
['__builtins__', '__name__', 'a', 'fib', 'fibo', 'sys']
>>> a = 5 # 建立一个新的变量 'a'
>>> dir()
['__builtins__', '__doc__', '__name__', 'a', 'sys']
>>>
>>> del a # 删除变量名a
>>>
>>> dir()
['__builtins__', '__doc__', '__name__', 'sys']
>>>

Standard module

Python itself with some of the standard library of modules in the Python Library Reference document will be introduced to (that is, behind the "Library Reference Document").

Some modules are built directly in the parser, though not some of these features built into the language, but he was able to very efficiently use, and even system-level calls, no problem.

These components will be different forms depending on the configuration of the operating system, such as the winreg module will only be available for Windows systems.

It should be noted that there is a special module sys, which is built into every Python parser. Sys.ps1 sys.ps2 variables and define the primary prompt string and the corresponding sub-prompt:

>>> import sys
>>> sys.ps1
'>>> '
>>> sys.ps2
'... '
>>> sys.ps1 = 'C> '
C> print('Runoob!')
Runoob!
C> 

package

Package is a namespace management module Python form, a "dot module name."

Such a module is the name AB, then he B A represents a sub-module package.

If using the module, you do not have to worry about global variables among different modules interaction, like the use of dotted module names in this form do not have to worry about the module between the different libraries of the same name.

Such different authors can provide the module NumPy or the Python graphics library.

Let's assume you want to design a uniform set of modules sound files and data processing (otherwise known as a "package").

The existing variety of different audio file formats (basically distinguished by extension, for example: .wav,: file: .aiff,: file: .au,), so you need to have a growing group of modules for conversion between different formats.

And for these audio data, there are a lot of different operations (such as mixing, adding echo, increase equalizer function to create artificial stereo effect), so you need never finish a set of modules how to handle these operations.

Here are a possible packet structure (hierarchical file system):

sound/                          顶层包
      __init__.py               初始化 sound 包
      formats/                  文件格式转换子包
              __init__.py
              wavread.py
              wavwrite.py
              aiffread.py
              aiffwrite.py
              auread.py
              auwrite.py
              ...
      effects/                  声音效果子包
              __init__.py
              echo.py
              surround.py
              reverse.py
              ...
      filters/                  filters 子包
              __init__.py
              equalizer.py
              vocoder.py
              karaoke.py
              ...

Importing a package in time, Python will come looking for this package contains subdirectories according to sys.path directories.

Only directory contains a file called __init__.py's only been recognized as a package, mainly to avoid some of the vulgar abuse of the name (for example, called string) careless affect the effective module search path.

In the simplest case, put an empty: file: __ init__.py it. Of course, this file may also contain some initialization code or a (which will be described later) __all__ is variable.

Introducing a specific user may be a time inside a package module, such as:

import sound.effects.echo

This will be imported sub-modules: sound.effects.echo. He must use the full name to access:

sound.effects.echo.echofilter(input, output, delay=0.7, atten=4)

Another method of introducing the sub-modules are:

from sound.effects import echo

It will also import sub-modules: echo, and he does not need those lengthy prefix, so he can use:

echo.echofilter(input, output, delay=0.7, atten=4)

Another change is introduced directly into a variable or function:

from sound.effects.echo import echofilter

Similarly, this approach is imported submodules: echo, and can directly use his echofilter () function:

echofilter(input, output, delay=0.7, atten=4)

Note that when using this form from package import item when the corresponding item inside the package may be a sub-modules (sub-packet), or other names defined inside the package, such as a function, class or variable.

The syntax will first import the item name as a package definition, if not found, then tried to follow a module to import. If not found, congratulations, a: exc: ImportError exception to be thrown.

Conversely, if the introduction of such import item.subitem.subsubitem shaped like form, except the last one, the package must be, and the last one may be a module or a package, but can not be a class name, a variable or function .


Import from a package *

Imagine if we use from sound.effects import * What will happen?

Python will enter the file system, find the package which all sub-modules, one by one they are imported in.

But unfortunately, it is not very good this works on Windows, because Windows is a case-insensitive system.

On this platform, no one can vouch file called ECHO.py is imported as a module echo Echo or even ECHO.

(For example, Windows 95 is very annoying to capitalize the first letter of each file is displayed) and DOS 8 + 3 naming convention will deal with the issue of long module names and made more tangled.

To solve this problem, only the troubles of the package provides an accurate index of the package.

Import statement to the following rules: If the package definition file called __init__.py there is a list of variables __all__, then put all the names in the list of imported when using from package import * as the package contents.

 

As the author of the package, do not forget after the update package to ensure __all__ also updated ah. You say I will not do it, I will not use the Import * This usage is, well, no problem, why did not you do the boss. Here is an example, in: init__.py contains the following code sounds / effects / __: file:

 

__all__ = ["echo", "surround", "reverse"]

This means that when you use this usage from sound.effects import *, you will only import the package inside the three sub-modules.

If  __all__  really is not defined, then use from sound.effects import * this syntax, it will not import the package sound.effects in any sub-module. He just put all the contents inside the package sound.effects and it came in the definition of import (defined in __init__.py may run initialization code).

All the names that will come in __init__.py which defines import. And he will not destroy us all explicitly specified modules imported before this sentence. Look at this part of the code:

import sound.effects.echo
import sound.effects.surround
from sound.effects import *

In this example, before performing Import from ..., the packet sound.effects echo and surround modules are introduced into the current namespace. (Of course, even if you define __all__ no problem)

Usually we do not advocate the use of * this method to import the module, because this method often leads to reduced readability of the code. But this is really a lot of effort can save keystrokes, and some modules are designed to become the only import through a specific method.

Remember, using from Package import specific_submodule this method will never be wrong. In fact, this is the recommended method. Unless you want to import sub-modules and sub-modules may have other packages of the same name.

If the structure of the package is a sub-package (such as the example for the package is sound), and you want to import the brothers package (same level package) you have to use imported absolute path to import. For example, if you want to use the module sound.filters.vocoder package sound.effects the module echo, you have to write from sound.effects import echo.

from . import echo
from .. import formats
from ..filters import equalizer

Whether implicit or explicit relative imports are from the beginning of the current module. The name of the main module is always "__main__", the main module of a Python application should always use absolute path references.

Package also provides an extra property __path__. This is a list of directories, each of which contains a directory of services have for this package __init__.py, you have to be executed before Oh defined in other __init__.py. This variable can be modified, and used to affect the sub-packets containing modules in the package inside.

This feature is not used, typically used to extend inside the package module.

Guess you like

Origin blog.csdn.net/u012717715/article/details/91972101