Module
Exit the Python interpreter and re-enter, the definition of functions and variables will be lost. The larger program uses a text editor to edit the file as a better execution input, which is to create the script. It can be split into several easier-to-maintain files when the program becomes very long. You might 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 a script or interpreter. Such a file is a module. The definitions in the module can be imported into other modules or the main module (that is, the set of variables that the top level of the script or the command line can access).
A module is a file that contains Python definitions and statements. The file name is the module name plus the. PY prefix. The module name can be obtained by the global variable name. Example: fibo.py:
# Fibonacci numbers moduledef fib (n): # write Fibonacci series up to n A, b = 0, 1 while b < N:print b , A, B = B, A+b 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 (+) 1 1 2 3 5 8 144 233 377 610 987>>> FIBO.FIB2 (100) [1, 1, 2, 3, 5, 8, 13, 89]>>> fibo.__name__ ' Fibo '
Aliases:
>>> fib = fibo.fib>>> fib (500) 1 1 2 3 5 8 13 21 34 55 89 144 233 377
In-depth modules
In addition to function definitions, a module can also contain executable statements. These statements are typically used to initialize a module. They are only executed on the first import. To forcibly load, you can use reload (modulename).
Each module has its own private symbol table, and all functions in the module use it as a global symbol table. Therefore, the use of global variables within the module does not conflict with the user's global variables. The global variables of the module can be referenced by Modname.itemname.
Other modules can be imported into the module. The recommended import is put on the head.
Another form of import: Not importing module names, directly importing functions, classes, variables, and so on.
>>> 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 the 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 allows you to import all names that are not preceded by an underscore. Because of poor readability, it is generally not recommended. However, it is not possible to save the deliverable session.
It is important to note that in practice it is often discouraged to use * import all from a module or package because it makes the code difficult to read. However, it is convenient in interactive sessions.
Execute the module in a scripted manner
Execution mode:
Python fibo.py <arguments>
The name is set to "main" so that execution is judged based on whether it is a master file. For example, add content to fibo.py:
if __name__ = = "__main__": Import sys fib (int (sys.argv[1]))
This is not done when importing, but executes as the primary file execution.
$ python fibo.py 501 1 2 3 5 8 34>>> Import fibo>>>
The search path for the module
When importing the spam module, the interpreter is first looked up in the built-in module and then Sys.path. The location defined by Sys.path is as follows:
Sys.path can be modified after initialization. Note Because the current directory has a higher priority, try not to have files with the same name as the other modules. This is a common mistake.
"Compiled" Python file
Python bytecode file suffix PYc, with the modified time as the version number, if the file is not modified, will call the PYc file instead of the Py file, instead of calling the Py file and generating pyc file, PYc file if the build failed also has no relationship. PHP needs to be compiled every time, so Python's efficiency is significantly higher than PHP.
Usually you do not need to do any work for creating SPAM.PYC files. Once spam.py compiles successfully, it tries to generate the corresponding version of SPAM.PYC. If for any reason the write is unsuccessful, the generated SPAM.PYC file is considered invalid and subsequently 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 tips:
Invoking the Python interpreter with the-o parameter generates the optimization code and is saved in the. pyo file. Currently only the Assert statement is deleted. The Pyo file has a higher priority than PYC.
-oo a deeper layer than-O, removing the document string. Because some programs depend on the availability of these variables, in some cases they can cause the program to fail to execute.
. PYc and. Pyo can only increase the load speed and cannot improve execution speed.
Specifies that the. pyc or. pyo file is not generated when the file name is executed at the command line. So the import action is better to put into the specialized importing module. Of course, you can also create. pyc or. pyo files manually.
You can increase the difficulty of reverse engineering by publishing only. PYc or. pyo files without releasing the py file.
The Compileall module creates a. pyc file for all modules in the specified directory (or creates a. pyo file with the-o parameter).
Standard modules
Python has some standard module library modules that are built into the interpreter for efficiency or system calls, some of which may not be cross-platform. Example WinReg module on a Windows system. There is a specific module worth noting: SYS's variables sys.ps1 and SYS.PS2 define the main prompt and the secondary prompt string:
>>> Import Sys
>>> SYS.PS1
' >>> '
>>> SYS.PS2
‘... ‘
>>> sys.ps1 = ' c> '
c> print ' yuck! '
yuck!
C>
These two variables are only meaningful in the interpreter's interactive mode.
The variable Sys.path is the Interpreter module search path. It is initialized by the environment variable PYTHONPATH, and if no PYTHONPATH is set, it is initialized by the built-in default value. You can modify it with the standard list operation:
>>> Import Sys
>>> sys.path.append ('/ufs/guido/lib/python ')
Dir () function
The built-in function dir () is used to view the definition of a module, which 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 no parameter is called, the Dir () function returns the list of current definitions:
>>> a = [1, 2, 3, 4, 5]
>>> Import Fibo
>>> fib = Fibo.fib
>>> dir ()
[' __builtins__ ', ' __name__ ', ' __package__ ', ' a ', ' fib ', ' Fibo ', ' sys ']
Note that the list lists all types of names: variables, modules, functions, and so on. Dir () does not list built-in functions and variable names. If you want to list these things, check out 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 '
Package
A package is a method for structuring the Python module namespace, in the form of a "dot module name." For example, A.B indicates that a module contains a B module. This avoids naming conflicts between multiple modules.
Suppose you now want to design a module set (package) to unify the processing of sound files and sound data. There are several different sound formats (usually identified by their extensions, for example:. wav,. AIFF,. au). To handle conversions between different types of file formats, you need to maintain a growing collection of modules. There are many different things to do with sound data (such as mixing, adding echoes, equalization, artistic effects), so a lot of modules are needed, and the structure is 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
...
The package directory must contain the init.py file, and the package looks like a module. This prevents unrelated package names from overriding the module name. Init.py can be an empty file, or it can have initialization code or set all variable.
Import specific modules in the package, for example:
Import Sound.effects.echo
This imports the Sound.effects.echo submodule. It must be referenced by a full name.
Sound.effects.echo.echofilter (input, output, delay=0.7, atten=4)
Another way:
From sound.effects import Echo
This can also be used without a package prefix:
Echo.echofilter (input, output, delay=0.7, atten=4)
Similarly, you can import functions or variables directly:
From Sound.effects.echo import Echofilter
Echofilter (input, output, delay=0.7, atten=4)
Note the item in the From package import item is either a sub-module (package) or another name defined in the package, such as a function, class, or variable. Import checks if there is a package and throws a Importerror exception if it is not loaded as a module and cannot be found.
Instead, each subkey in the import Item.subitem.subsubitem must be a package, and the last subkey can be a package or module, but not a class, function, or variable.
Import *
It appears that the from sound.effects import * Imports all submodules and takes a long time, but the package is handled according to the all list.
If all is defined for the init.py file of the effects directory, the above command will only import the sub-modules for that list. Like what:
__all__ = ["echo", "surround", "reverse"]
If all is not defined, the FROM sound.effects import * statement does not import all submodules from the sound.effects package, it only guarantees the import of sound.effects, executes the init.py, and imports the previously imported modules:
Import Sound.effects.echo
Import Sound.effects.surround
From sound.effects Import *
Import * is not a suggested notation. Recommended from the package import Specific_submodule, but mainly do not have the same name.
In-Package references
Absolute path:
From sound.effects import Echo
Relative path:
From. Import Echo
From.. Import formats
From.. Filters Import Equalizer
Reference
The special properties of the package path specifies the directory containing the init.py file in the package, which can be modified for expansion, but is seldom used
Resources
Author Blog: http://my.oschina.net/u/1433482
-
contact Xu Rongzhong python development Automation test group 113938272 Weibo Http://weibo.com/cizhenshi.
Python 2.7 Official English tutorial: https://docs.python.org/2/tutorial/
Python 2.7 Chinese tutorials and automated Testing introduction (4)