Python3 module

Programming with the python interpreter, if you exit and enter from the python interpreter, all the methods and variables you defined are gone.

For this purpose Python provides a way to store these definitions in a file, called a module , for use by some script or interactive interpreter instance .

A module is a file that contains all the functions and variables you define, with the extension .py. Modules can be imported by other programs to use functions such as functions in that module. This is also the way to use the python standard library.

#import sys 引入 python 标准库中的 sys.py 模块;这是引入某一模块的方法。
import sys

print('命令行参数如下:')
for i in sys.argv: #sys.argv 是一个包含命令行参数的列表。
   print(i)

#sys.path 包含了一个 Python 解释器自动查找所需模块的路径的列表。
print('\n\nPython 路径为:', sys.path, '\n')

import statement

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

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

The search path is a list of all directories that the interpreter will search first. If you want to import the module support, you need to put the command at the top of the script: The code of the support.py file is:

# Filename: support.py

def print_func( par ):
    print ("Hello : ", par)
    return

test.py introduces the support module:

# 导入模块
import support
 
# 现在可以调用模块里包含的函数了
support.print_func("Runoob")

A module will only be imported once, no matter how many times you import it. This prevents imported modules from being executed over and over again.

When we use the import statement, how does the Python interpreter find the corresponding file?

This involves Python's search path. The search path consists of a series of directory names, and the Python interpreter searches these directories in turn to find the imported modules.

This looks a lot like an environment variable, and in fact, the search path can also be determined by defining an environment variable.

The search path is determined when Python is compiled or installed, and should be modified when installing new libraries. The search path is stored in the path variable in the sys module. To do a simple experiment, in the interactive interpreter, enter the following code:

>>> import sys
>>> sys.path
['', 'C:\\Program Files\\Python36\\Lib\\idlelib', 'C:\\Program Files\\Python36\\python36.zip', 'C:\\Program Files\\Python36\\DLLs', 'C:\\Program Files\\Python36\\lib', 'C:\\Program Files\\Python36', 'C:\\Program Files\\Python36\\lib\\site-packages']
>>> 

The output of sys.path is a list, the first item of which is an empty string '', representing the current directory (if it is printed from a script, it can be more clearly seen which directory is), that is, we execute the python interpreter. Directory (in the case of scripts, the directory where the running script is located).

Therefore, if there is a file with the same name as the module to be imported in the current directory like me, the module to be imported will be blocked.

Once you understand the concept of search paths, you can modify sys.path in your script to introduce some modules that are not in the search path.

Now, create a fibo.py file in the current directory of the interpreter or a directory in sys.path with the following code:

# 斐波那契(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

Then go into the Python interpreter and import the module with the following command:

>>> import fibo

Doing so does not write the names of functions defined directly in fibo into the current symbol table, only the name of the module fibo is written there.

Functions can be accessed using the module name:

>>> 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 plan to use a function frequently, you can assign it 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 section from a module into the current namespace. The syntax is as follows:

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

For example, to import the fib function of the module fibo, 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 declaration does not import the entire fibo module into the current namespace, it only imports the fib function from fibo.

from…import * statements

It is also possible to import the entire contents of a module into the current namespace, just use the following declaration:

from modname import *

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

deep module

In addition to method definitions, modules can also contain executable code. These codes are generally used to initialize the module. This code will only be executed the first time it is imported.

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

__name__ attribute

When a module is first introduced by another program, its main program will run. If we want a block in the module not to be executed when the module is imported, we can use the __name__ attribute to make the block execute only when the module itself is running.

# Filename: using_name.py

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

The output of running is as follows:

$ python using_name.py
程序自身在运行

$ python
>>> import using_name
我来自另一模块
>>>

Description: Each module has a __name__ attribute, when its value is ' main ', it indicates that the module itself is running, otherwise it is imported.

Description: __name__ and __main__ are double underscores, and _ _ removes the space in the middle.

dir() function

The built-in function dir() finds all names defined within a module. Return as a list of strings:

>>> 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 arguments are given, the dir() function will list all currently defined names:

>>> 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 comes with some standard module libraries, which will be introduced in the Python library reference documentation (the "Library Reference Documentation" later).

Some modules are built directly in the parser. Although these are not built-in functions of some languages, they can be used very efficiently, and even system-level calls are no problem.

These components will be configured in different forms according to different operating systems. For example, the winreg module will only be provided to Windows systems.

It should be noted that there is a special module sys that is built into every Python parser. The variables sys.ps1 and sys.ps2 define the strings corresponding to the primary and secondary prompts

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

Bag

A package is a form of managing the Python module namespace, taking the "dot module name".

For example, the name of a module is AB, then he represents a submodule B in a package A.

Just like when using modules, you don't have to worry about the interaction of global variables between different modules, and you don't have to worry about the same name of modules between different libraries by using the dot module name.

Let's say you want to design a set of modules (or call it a "package") that handles sound files and data in a unified way.

There are many different audio file formats (basically differentiated by their suffix, e.g. .wav, :file:.aiff, :file:.au, ), so you need to have a growing set of modules for Convert between different formats.

And with this audio data, there are many different operations (such as mixing, adding echo, adding equalizer functions, creating artificial stereo effects), so you also need an endless set of modules to handle these operations.

Here is a possible package structure (in a layered filesystem):

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
              ...

When importing a package, Python looks for the subdirectories contained in the package based on the directories in sys.path.

A directory will only be considered a package if it contains a file called __init__.py, mainly to avoid vulgar names (such as strings) from inadvertently affecting valid modules in the search path.

In the simplest case, just put an empty :file:__init__.py. Of course, this file can also contain some initialization code or assign values ​​to the __all__ variable (described later).

Users can only import specific modules in one package at a time, for example:

import sound.effects.echo

This will import the submodule: sound.effects.echo. It must be accessed using the full name: sound.effects.echo.echofilter(input, output, delay=0.7, atten=4)

Another way to import submodules is:

from sound.effects import echo

This also imports the submodule: echo, and it doesn't need those verbose prefixes, so it can be used like this:

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

Another variation is to directly import a function or variable:

from sound.effects.echo import echofilter

Again, this method imports the submodule: echo, and can use its echofilter() function directly:

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

Note that when using the form from package import item, the corresponding item can be either a submodule (subpackage) in the package, or other names defined in the package, such as functions, classes or variables.

The import syntax will first treat item as the name of a package definition, and if not found, try to import it as a module. If it hasn't been found, congratulations, an :exc:ImportError exception was thrown.

Conversely, if you use an import form such as import item.subitem.subsubitem, all but the last item must be a package, and the last item can be a module or a package, but not the name of a class, function or variable .

import * and __all__ from a package

Imagine what would happen if we used from sound.effects import *?

Python will enter the file system, find all the submodules in the package, and import them one by one.

Unfortunately, this method doesn't work very well on Windows because Windows is a case-insensitive system.

On such platforms, no one can guarantee that a file called ECHO.py imports as a module echo or Echo or even ECHO.

(Windows 95, for example, hates to capitalize the first letter of every file) and DOS's 8+3 naming convention for long module names makes the problem even more confusing.

In order to solve this problem, we can only trouble the package author to provide an accurate package index.

The import statement follows the following rules: If there is a list variable called __all__ in the package definition file __init__.py, then when using from package import *, all names in this list are imported as package contents.

As the author of the package, don't forget to make sure __all__ is also updated after updating the package. You say I don't do it, I don't use import * this usage, well, no problem, who made you the boss. Here is an example with the following code in :file:sounds/effects/__init__.py:

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

This means that when you use from sound.effects import * you will only import these three submodules in the package.

If __all__ is really undefined, then using the syntax from sound.effects import * will not import any submodules in the package sound.effects. He just imports the package sound.effects and everything defined in it (perhaps running the initialization code defined in __init__.py).

This will import all the names defined in __init__.py. And it won't break all the explicitly specified modules we imported before this sentence. Take a look at this part of the code:

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

In this example, both the echo and surround modules in the package sound.effects are imported into the current namespace before the from...import is executed. (Of course, if __all__ is defined, it will be fine)

Usually we do not advocate using * this method to import modules, because this method often leads to less readable code. However, this does save a lot of keystrokes, and some modules are designed to be imported only through specific methods.

Remember, you can never go wrong using from Package import specific_submodule. In fact, this is also the recommended method. Unless the submodule you want to import may have the same name as the submodules of other packages.

If the package is a subpackage in the structure (such as the package sound in this example), and you want to import a sibling package (a package of the same level) you have to use the import absolute path to import it. For example, if the module sound.filters.vocoder were to use the module echo from the package sound.effects, you would write from sound.effects import echo.

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

Relative imports, whether implicit or explicit, start from the current module. The name of the main module is always "__main__", and the main module of a Python application should always be referenced using an absolute path.

__path__

The package also provides an additional attribute __path__. This is a list of directories, each of which contains an __init__.py for this package, which you must define before other __init__.py are executed. This variable can be modified to affect the modules and subpackages contained within the package.

This function is not commonly used, and is generally used to extend the modules in the package.

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=324980213&siteId=291194637