Pthon3 Test Tool Development Quick Start Tutorial 6 Modules

Modular

Exit the Python interpreter and reenter, definitions of functions, variables, and so on will be lost.It is better for larger programs to use files edited by a text editor as execution input, that is, to create scripts.When a program becomes very long, it can be split into several files that are easier to maintain.You may also want to use the same function in several programs instead of copying the code.

Python can be defined in a file and used in scripts or interpreters.Such a file is a module.Definitions in modules can be imported into other modules or main modules (that is, sets of variables accessible at the top level of the script or from the command line).

A module is a file that contains Python definitions and statements.The file name is the module name with the.Py affix.The module name can be obtained from the global variable name.Example: fibo.py:

# Fibonacci numbers module

def fib(n):    # write Fibonacci series up to n
    a, b = 0, 1
    while b < n:
        print(b, end=' ')
        a, b = b, a+b
    print()

def fib2(n):   # return Fibonacci series up to n
    result = []
    a, b = 0, 1
    while b < n:
        result.append(b)
        a, b = b, a+b
    return result

Command line import:

>>> import fibo

call

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

Alias:

>>> fib = fibo.fib
>>> fib(500)
1 1 2 3 5 8 13 21 34 55 89 144 233 377

Deep module

In addition to function definitions, modules can also contain executable statements.These statements are typically used to initialize modules.They are only executed on the first import.To force a load, you can use reload(modulename).

Each module has its own private symbol table, which is used as a global symbol table by all functions within the module.Therefore, global variables used within a module do not conflict with the user's global variables.Module global variables can be referenced through modname.itemname.

Other modules can be imported into the module.Imports are recommended at the head.

Another form of import is to import functions, classes, variables, and so on directly without importing the module name.

>>> from fibo import fib, fib2
>>> fib(500)
1 1 2 3 5 8 13 21 34 55 89 144 233 377

This does not import the module name from the local semantic table (as shown above, fibo is not defined).

There is even a way to import all the definitions in a module:

>>> from fibo import fib, fib2
>>> fib(500)
1 1 2 3 5 8 13 21 34 55 89 144 233 377

You can also import all non-private definitions:

>>> from fibo import *
>>> fib(500)
1 1 2 3 5 8 13 21 34 55 89 144 233 377

This imports all naming that does not begin with an underscore.Usually not recommended because of poor readability.However, it is not possible to save a delivery session.
It is important to note that in practice you are not always encouraged to use * to import everything from a module or package, as this makes the code hard to read.However, it is convenient in interactive conversations.

Executing modules in a scripted manner

Execution method:

python3 fibo.py <arguments>

At this point, the name is set to "main" so that execution is determined by whether or not it is the main file.For example, add content in fibo.py:

if __name__ == "__main__":
    import sys
    fib(int(sys.argv[1]))

This will not be done when importing, but will be done when executing as the main file.

$ python3 fibo.py 50
1 1 2 3 5 8 13 21 34
>>> import fibo
>>>

Search path for module

When importing a module, the interpreter first looks in the built-in module, then sys.path.The location defined by sys.path is as follows:

  • current directory

  • PYTHONPATH variable (shell-like PATH)

  • Python default installation directory

You can modify sys.path after initialization.Note that because the current directory has a higher priority, try not to have files with the same name as other modules.This is a common error.

Compiled: Python file

pyc files can speed up the loading of a large number of short programs that reference standard modules.It is considered a pre-compiled (binary compiled) version of the source code.python's byte code file is suffixed with pyc to use the modification time as the version number. If the file is not modified, the pyc file will be invoked directly instead of the py file. Conversely, the pyc file will be invoked and the pyc file will be generated. It does not matter if the pyc file fails to generate.PHP needs to be compiled every time, so python is significantly more efficient than PHP.

Normally you don't need to do anything to create a spam.pyc file.Once spam.py is compiled successfully, an attempt is made to generate the corresponding version of spam.pyc.If for any reason the write is unsuccessful, the spam.pyc file generated is considered invalid and then ignored.The content of the spam.pyc file is platform independent, so the Python module directory can be shared between machines with different architectures.

Some advanced techniques:

When the Python interpreter is called with the -O parameter, the optimization code is generated and saved in a.pyo file.Currently, only assert statements have been deleted.pyo files take precedence over pyc.
-OO is deeper than-O, deleting the document string.Because some programs depend on the availability of these variables, in some cases they will fail to execute.
.pyc and.pyo only increase load speed, not execution speed.
The specified file name will not generate a.pyc or.pyo file when executed from the command line.So it's better to put the import action into a dedicated import module.Of course, you can also create a.pyc or.pyo file by hand.
It is more difficult to reverse engineer by publishing only.pyc or.pyo files instead of py files.
The compileall module creates a.pyc file (or a.pyo file with the -O parameter) for all modules in the specified directory.

Standard Module

For Python's documentation, see the Standard Module Library ( Python Library Reference ).Some standard module library modules are built into interpreters for efficiency or access to system primitives, such as system calls, but are not at the core of python, noting that some modules may not be cross-platform.The example winreg module is only available on Windows systems.There is a specific module to note: sys variables sys.ps1 and sys.ps2 define the primary prompt and secondary prompt strings:

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

These two variables only make sense in interactive mode.

The variable sys.path is the interpreter module search path.It is initialized by the environment variable PYTHONPATH, or by a built-in default value if PYTHONPATH is not set.You can modify it using standard list operations:

>>> import sys
>>> sys.path.append('/ufs/guido/lib/python')

dir() function

The built-in function dir() looks at the definition of a module and returns a sorted list of strings:

>>> import fibo, sys
>>> dir(fibo)
['__name__', 'fib', 'fib2']
>>> dir(sys)  
['__displayhook__', '__doc__', '__excepthook__', '__name__', '__package__',
 '__stderr__', '__stdin__', '__stdout__', '_clear_type_cache',
 '_current_frames', '_getframe', '_mercurial', 'api_version', 'argv',
 'builtin_module_names', 'byteorder', 'call_tracing', 'callstats',
 'copyright', 'displayhook', 'dont_write_bytecode', 'exc_clear', 'exc_info',
 'exc_traceback', 'exc_type', 'exc_value', 'excepthook', 'exec_prefix',
 'executable', 'exit', 'flags', 'float_info', 'float_repr_style',
 'getcheckinterval', 'getdefaultencoding', 'getdlopenflags',
 'getfilesystemencoding', 'getobjects', 'getprofile', 'getrecursionlimit',
 'getrefcount', 'getsizeof', 'gettotalrefcount', 'gettrace', 'hexversion',
 'long_info', 'maxint', 'maxsize', 'maxunicode', 'meta_path', 'modules',
 'path', 'path_hooks', 'path_importer_cache', 'platform', 'prefix', 'ps1',
 'py3kwarning', 'setcheckinterval', 'setdlopenflags', 'setprofile',
 'setrecursionlimit', 'settrace', 'stderr', 'stdin', 'stdout', 'subversion',
 'version', 'version_info', 'warnoptions']

When called without parameters, the dir() function returns a list of currently defined names:

>>> a = [1, 2, 3, 4, 5]
>>> import fibo
>>> fib = fibo.fib
>>> dir()
['__builtins__', '__name__', '__package__', 'a', 'fib', 'fibo', 'sys']

Notice that the list lists all types of names: variables, modules, functions, and so on.dir() does not list built-in function and variable names.If you want to list these, just look at builtin:

>>> import __builtin__
>>> dir(__builtin__)  
['ArithmeticError', 'AssertionError', 'AttributeError', 'BaseException',
 'BufferError', 'BytesWarning', 'DeprecationWarning', 'EOFError',
 'Ellipsis', 'EnvironmentError', 'Exception', 'False', 'FloatingPointError',
 'FutureWarning', 'GeneratorExit', 'IOError', 'ImportError', 'ImportWarning',
 'IndentationError', 'IndexError', 'KeyError', 'KeyboardInterrupt',
 'LookupError', 'MemoryError', 'NameError', 'None', 'NotImplemented',
 'NotImplementedError', 'OSError', 'OverflowError',
 'PendingDeprecationWarning', 'ReferenceError', 'RuntimeError',
 'RuntimeWarning', 'StandardError', 'StopIteration', 'SyntaxError',
 'SyntaxWarning', 'SystemError', 'SystemExit', 'TabError', 'True',
 'TypeError', 'UnboundLocalError', 'UnicodeDecodeError',
 'UnicodeEncodeError', 'UnicodeError', 'UnicodeTranslateError',
 'UnicodeWarning', 'UserWarning', 'ValueError', 'Warning',
 'ZeroDivisionError', '_', '__debug__', '__doc__', '__import__',
 '__name__', '__package__', 'abs', 'all', 'any', 'apply', 'basestring',
 'bin', 'bool', 'buffer', 'bytearray', 'bytes', 'callable', 'chr',
 'classmethod', 'cmp', 'coerce', 'compile', 'complex', 'copyright',
 'credits', 'delattr', 'dict', 'dir', 'divmod', 'enumerate', 'eval',
 'execfile', 'exit', 'file', 'filter', 'float', 'format', 'frozenset',
 'getattr', 'globals', 'hasattr', 'hash', 'help', 'hex', 'id', 'input',
 'int', 'intern', 'isinstance', 'issubclass', 'iter', 'len', 'license',
 'list', 'locals', 'long', 'map', 'max', 'memoryview', 'min', 'next',
 'object', 'oct', 'open', 'ord', 'pow', 'print', 'property', 'quit',
 'range', 'raw_input', 'reduce', 'reload', 'repr', 'reversed', 'round',
 'set', 'setattr', 'slice', 'sorted', 'staticmethod', 'str', 'sum', 'super',
 'tuple', 'type', 'unichr', 'unicode', 'vars', 'xrange', 'zip']

Reference material

package

Packages are a way to structure python module namespaces using the dot module name format, such as A.B, which means that A module contains B submodules.This avoids naming conflicts between multiple modules.

Suppose you want to design a module set (package) to process sound files and data in a unified way.There are several different sound formats (usually identified by their extensions, e.g..Wav,.Aiff,.Au).To handle the conversion between different file formats, you need to maintain a growing collection of modules.There are also many different operations on sound data (such as mixing, adding echo, balancing, artistic effects), so a lot of modules are needed, structured as follows:

sound/                          Top-level package
      __init__.py               Initialize the sound package
      formats/                  Subpackage for file format 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
              equalizer.py
              vocoder.py
              karaoke.py
              ...

When importing a package, Python uses sys.path to find the corresponding subdirectory.

The package directory must contain an init.py file to avoid overwriting the module name with a common directory name._u init_u.py can be an empty file, have initialization code, or set all variable.

Specific modules in the package can be imported, for example:

import sound.effects.echo

This imports the sound.effects.echo submodule.It must be referenced by its full name.

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

Another way:

from sound.effects import echo

This can be used without a package prefix:

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

Similar functions or variables can be imported directly:

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

Note that the item in from package import item can be either a submodule (package) in the package or another name defined in the package, such as a function, class, or variable.Import checks the package for presence first, and if it is not loaded as a module and cannot be found, it raises an ImportError exception.

Instead, each subitem in import item.subitem.subsubitem must be a package, and the last subitem can be a package or module, but not a class, function, or variable.

import *

It looks like from sound.effects import * will import all the sub-modules, which will take a long time.However, defining a u all_u list in the package prevents all imports.For example, if the init.py file of the effects directory defines u all_u, the above command will only import the corresponding submodules of the list.

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

If u all_u is not defined, the from sound.effects import * statement does not import all the sub-modules from the sound.effects package. It only guarantees that sound.effects are imported and that _init_u.py is executed:

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

Import * is not recommended.from Package import specific_submodule is recommended, but be careful not to have duplicate names.

In-Package References

Absolute path:
 from sound.effects import echo
Relative path:
    from . import echo
    from .. import formats
    from ..filters import equalizer

It is important to note that all imports are named based on the current module, usually "u main_u", and that the main module should always use absolute paths.

Multi-directory package

The special property u path_u of a package specifies the directory in which the package contains the init.py file, which is easy to expand, but rarely used

Keywords: Python PHP Session shell

Added by wei on Wed, 15 May 2019 00:27:56 +0300