Python BASICS (12)-module, python basics-Module

Source: Internet
Author: User

Python BASICS (12)-module, python basics-Module

URL: http://www.cnblogs.com/archimedes/p/python-modules.html.

Module Introduction

If you exit the Python interpreter and re-enter, all previously created definitions (variables and functions) will be lost. Therefore, if you want to write a program that has been saved for a long time, you 'd better use a text editor to write the program and input the saved file into the interpreter. This is called creatingScript. The program has become longer, and you may separate it into several files for convenient maintenance. You may also want to use a common function in several programs, but do not want to copy its definition to every program.

To meet these requirements, Python provides a method to get definitions from files and use them in an interactive instance of a script or interpreter. Such a file is calledModuleThe definition in the module can beImportTo another module or main module (the variable set that can be called during script execution is at the highest level and in calculator mode)

A module is a file that includes Python definitions and declarations. The file name is the module name with the. py suffix. The module name (as a string) can be composed of global variables.__name__. For example, you can use your usual file editor to create a file named fibo. py in the current directory and enter the following content:

# Fibonacci numbers moduledef fib(n):    # write Fibonacci series up to n    a, b = 0, 1    while b < n:        print b,        a, b = b, a+bdef 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

Enter the Python interpreter and run the following command to import the module:

>>> import fibo

In this wayfiboFunction to import the current semantic table; it only introduces the module namefibo. You can access this function using the module name as follows:

>>> fibo.fib(1000)1 1 2 3 5 8 13 21 34 55 89 144 233 377 610 987>>> print '\n',fibo.fib2(100)[1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89]>>> fibo.__name__'fibo'

If you want to directly call a function, you can usually assign it a local name:

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

A module can include execution statements like a function definition. These statements are usually used to initialize the module. They are only in the moduleFirst timeRun the command once during import.

Corresponds to the Global Semantic table of all functions in the definition module. Each module has its own private semantic table. Therefore, the module Author can use some global variables in the module to avoid errors caused by conflicts with the user's global variables.

On the other hand, if you are sure you need this, you can obtain the global variables in the module just as you reference the functions in the module, such:modname.itemname.

You can import other modules. Used to allImportStatements are placed at the beginning of a module (or script, etc.), but this is not necessary. The imported Module name is in the Global Semantic table of this module.

ImportA variant of the statement is directly imported from the imported module to the semantic table of this module. For example:

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

This will not import the module name from the local semantic table (as shown above,fiboNot defined ). In this way, you can import all (_.

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

In this way, you can import all (_.

Module search path

Import a file namedSpamModule, the interpreter first searches for the file spam. py in the current directory, then searches for the directory list in the environment variable PYTHONPATH, and then the PATH list in the environment variable PATH. If the PYTHONPATH is not set or the file is not found, search for the installation directory.

In fact, the interpreter consistssys.pathThe path Directory Search module specified by the variable. The variable initialization contains input scripts (or the current directory), PYTHONPATH, and installation directory by default. This allows the Python Program (in the original article, programs; I guess it should be "programer", programmer-translator) to understand how to modify or replace the module search directory. Note that these directories contain scripts running in the search path, so these scripts should not be named again with the standard module, otherwise, Python will try to load these scripts as modules when importing the module. This usually leads to an error.

"Compile" Python files

For short programs that reference a large number of standard modules, there is an important way to increase the startup speed, if. the directory where py is located contains a file named spam. pyc file, which is consideredSpamThe pre-"compiled" version of the module. The modification time of this version of spam. py used to create spam. pyc is recorded in the spam. pyc file. If the two do not match, the. pyc file is ignored.

Generally, you do not need to do any work for creating the spam. pyc file. Once spam. py is successfully compiled, it will try to compile the corresponding version of spam. pyc. If the write operation fails for any reason, the returned spam. pyc file is regarded as invalid and then ignored. The content of the spam. pyc file is platform independent, so the Python Module Directory can be shared between machines of different architectures.

Some advanced skills:

  • To-OWhen the parameter calls the Python interpreter, the optimization code is generated and saved in the. pyo file. The current optimizer does not help much; it just deletes assertions (Assert) Statement. Use-OParameter. All codes are optimized;.pycFile ignored,.pyThe file is compiled as the optimization code.

  • Pass two to the Python Interpreter-OParameters (-OOWill execute a fully optimized binary optimization compilation, which occasionally generates an incorrect program. The optimizer is deleted from the binary code.__doc__String to generate a more compact. pyo file. Because some programs depend on the availability of these variables, you should only use this option when there is no error.

  • Programs from the. pyc file or. pyo file will not run faster than those from the. py file;. pyc or. pyo files will only run faster when they are loaded.

  • When you run the script through the script name in the command line, the binary code created for the script will not be written to the. pyc or. pyo file. Of course, moving the main code of the script into a module, and then using a small deconstruct script to import the module can increase the startup speed of the script. You can also specify a. pyc or. pyo file in the command line.

  • For the same module (spam. py in this example), only the spam. pyc file (or spam. pyc) can be used.-OParameter) without the spam. py file. This allows you to package and release Python code libraries that are difficult to reverse engineer.

  • The module can create a. pyc file for all modules in the specified directory (or use the. pyo parameter to create a. pyo file ).

Standard Module

Python comes with a standard module library and has released an independent document namedPythonLibrary Reference Manual (hereinafter referred to as "Library Reference Manual "). Some modules are built into the interpreter. The access interfaces for these operations are not part of the language kernel, but are already built into the interpreter. This is not only to improve efficiency, but also to provide interfaces for native access to operating systems such as system calls. This type of module set is a configuration option that depends on the underlying platform. For example,AmoebaThe module only supports the Amoeba native system. There is a specific module worth noting:SysThis module is built into all Python interpreters. Variablesys.ps1Andsys.ps2The main prompt and secondary prompt strings are defined:

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

These two variables only make sense in the interaction mode of the interpreter.

Variablesys.pathIs the string list of the interpreter module's search path. It is initialized by the Environment Variable PYTHONPATH. If PYTHONPATH is not set, it is initialized by the built-in default value. You can modify it using a standard string:

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

Example 1: Use the sys module

import sysprint 'the command line arguments are:'for i in sys.argv:    print iprint '\n\nThe PYTHONPATH is',sys.path, '\n'

The running result is as follows:

The command line arguments are:
F:/PycharmProjects/Pytest/test. py


The PYTHONPATH is ['f: \ PycharmProjects \ pytest', 'c: \ Python27 \ lib \ site-packages \ distribute-0.6.27-py2.7.egg ', 'c: \ Python27 \ Lib \ site-packages \ wx-3.0-msw ', 'd: \ chardet-2.3.0', 'f: \ PycharmProjects \ pytest', 'c: \ Windows \ system32 \ python27.zip ', 'c: \ Python27 \ DLLs', 'c: \ Python27 \ lib ', 'c: \ Python27 \ lib \ plat-win ', 'c: \ Python27 \ lib-tk', 'c: \ python27', 'c: \ Python27 \ lib \ site-packages ', 'c: \ Python27 \ lib \ site-packages \ setuptools-0.6c11-py2.7.egg-info']

Dir ()Function

The built-in functionDir ()Is used to find out which names a module defines. It returns a sorted list of strings:

Built-in functionsDir ()It is used to search for module definitions by module name. It returns a string type storage list:

import fibo,sysprint dir(fibo)print '\n',dir(sys)

The running result is as follows:

['__builtins__', '__doc__', '__file__', '__name__', '__package__', 'fib', 'fib2']['__displayhook__', '__doc__', '__egginsert', '__excepthook__', '__name__', '__package__', '__plen', '__stderr__', '__stdin__', '__stdout__', '_clear_type_cache', '_current_frames', '_getframe', '_mercurial', 'api_version', 'argv', 'builtin_module_names', 'byteorder', 'call_tracing', 'callstats', 'copyright', 'displayhook', 'dllhandle', 'dont_write_bytecode', 'exc_clear', 'exc_info', 'exc_type', 'excepthook', 'exec_prefix', 'executable', 'exit', 'flags', 'float_info', 'float_repr_style', 'getcheckinterval', 'getdefaultencoding', 'getfilesystemencoding', 'getprofile', 'getrecursionlimit', 'getrefcount', 'getsizeof', 'gettrace', 'getwindowsversion', 'hexversion', 'long_info', 'maxint', 'maxsize', 'maxunicode', 'meta_path', 'modules', 'path', 'path_hooks', 'path_importer_cache', 'platform', 'prefix', 'py3kwarning', 'setcheckinterval', 'setprofile', 'setrecursionlimit', 'settrace', 'stderr', 'stdin', 'stdout', 'subversion', 'version', 'version_info', 'warnoptions', 'winver']

When no parameter is called,Dir ()The function returns the name of the current definition:

a=[1,2,3,4,5]import fibo,sysfibo=fibo.fibprint dir()

The running result is as follows:

['__builtins__', '__doc__', '__file__', '__name__', '__package__', 'a', 'fibo', 'sys']

The list lists all types of names: variables, modules, functions, and so on:

Dir ()Built-in functions and variable names are not listed. If you want to list these contents, they are in the standard module_ Builtin __Definition:

>>> import __builtin__>>> dir(__builtin__)

The running result is as follows:

['Arithmeticerror', 'assertionerror', 'bubuteerror', 'baseexception', 'buffererror', 'byteswarning', 'describecationwarning', 'eoferror', 'ellipsis ', 'environmentererror', 'exception', 'false', 'floatingpointerror ', 'ureurewarning', 'generatorexit', 'ioerror', 'importererror', 'importwarning', 'indentationerror ', 'indexerror', 'keyerror', 'keyboardinterrupt', 'lookuperror ', 'memoryerror', 'nameerror', 'none', 'notimplemented', 'notimplementederror', 'oserror ', 'overflowerror', 'signature', 'referenceerror', 'runtimeerror', 'runtimewarning', 'standardererror', 'stopiteration', 'syntaxerror', 'syntaxwarning', 'systemerror ', 'systemdelete', 'taberror', 'true', 'typeerror', 'unboundlocalerror', 'unicodeerror', 'unicodeerror', 'unicodetranslateerror', 'unicodewarning ', 'userwarning', 'valueerror', 'warning', 'windowserror ', 'zerodivisionerror',' _ debug _ ',' _ doc __', '_ import _', '_ name _', '_ package _', 'abs ', 'all', 'any', 'application ', 'basestring', 'bin', 'bool ', 'buffer', 'bytearray', 'bytes', 'callable', 'chr', 'classmethod', 'cmp ', 'coerce ', 'compile', 'compute', 'copyright', 'credit', 'delattr', 'dict ', 'dir', 'didmod', 'enumerate ', 'eval', 'execfile', 'exit ', 'file', 'filter', 'float', 'format', 'frozenset', 'getattr', 'globals ', 'hasattr', 'hash', 'help', 'hex', 'id', 'input', 'intern', 'isinstance', 'issubclass ', 'iter ', 'len', 'license', 'LIST', 'locals', 'long', 'map', 'max ', 'memoryview', 'Min ', 'Next', 'object', 'oct', 'open', 'ord ', 'pow', 'print', 'properties', 'quit', 'range ', 'raw _ input', 'reduce', 'reload', 'repr', 'reversed ', 'round', 'set', 'setattr ', 'slice ', 'sorted', 'staticmethod', 'str', 'sum', 'super', 'tuple', 'type', 'unichr', 'unicode ', 'vars ', 'xrange', 'zip']

Packages

A package usually uses a structured module namespace with the "dot Module name. For exampleA. BThe module is named"B"Package name"A. Just as using modules to save different module architectures can avoid conflicts between global variables, using the dot Module name to save different class Library architectures such as NumPy or Python Imaging Library can avoid name conflicts between modules.

Suppose you want to design a module set (a "package") to process audio files and sound data in a unified manner. There are several different sound formats (usually identified by their extensions, for example :. wav ,. aiff ,. (au), so to convert different types of file formats, you need to maintain a growing set of packages. You may also want to perform many different operations on sound data (such as mixing, adding echo, applying the balance function, and creating a person-created effect ), therefore, you need to add an infinite stream module to perform these operations. Your package may look like this (grouping through a hierarchical file system ):

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 module, Python usessys.pathIn the directory list to search for the subdirectories of the stored package.

A _ init _. py file must exist before Python can regard the directory as a package. This is to prevent some directories from being used"String"This generic name inadvertently overwrites the correct module in the subsequent module search path. In the simplest case, __init _. py can be just an empty file, but it may also contain the package initialization code or set__all__Variable, which will be described later. Package users can import valid modules from the package, for example:

import Sound.Effects.echo

In this way, the data is imported.Sound. Effects. echoSub-module. It must be referenced by a complete name.

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

You can select the following method when importing a package:

from Sound.Effects import echo

This LoadsEchoSub-module, which can be used without the package prefix, so it can be called as follows:

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

Another variant is used to directly import functions or variables:

from Sound.Effects.echo import echofilter

In this way, the load is loaded again.EchoSub-module, but you can directly call itsEchofilter ()Function:

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

Note thatfrom package import itemWhen importing a package, this item can be either a sub-module (or a sub-Package) in the package or another name defined in the package, such as functions, classes, or variables.importThe statement first checks whether the package contains this subitem. If not, it assumes that this is a module and tries to load it. If it is not found,ImportErrorException.

On the contraryimport item.subitem.subsubitemIn this syntax, these subitems must be packages, and the last subitem can be a package or module, but not a class, function, or variable defined in the previous subitem.

You may also be interested in:

Python BASICS (11) -- object-oriented 1

Python BASICS (10)-Numbers

Python BASICS (9) -- Regular Expressions

Python BASICS (8)-Files

Python BASICS (7) -- Functions

Python BASICS (6) -- conditions and loops

Python BASICS (5)-dictionary

Python BASICS (4) -- strings

Python BASICS (3) -- list and metadata

Python BASICS (2) -- Object Type

Python BASICS (1) -- Python programming habits and features

 

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.