Python automated Transport Koriyuki module and package usage

Source: Internet
Author: User
Tags define function naming convention

First, the module
1. What is a module?
A module is a file that contains the Python definition and declaration, and the filename is the suffix of the module name plus the. Py.
2. Why should I use the module?
If you quit the Python interpreter and then re-enter, then the functions or variables you defined previously will be lost, so we usually write the program to a file so that it can be persisted and executed in Python test.py when needed, when test.py is called a scripting script.

With the development of the program, more and more functions, in order to facilitate management, we usually divide the program into a file, so that the structure of the program is clearer and easier to manage. At this point, we can not only use these files as scripts to execute, but also as a module to import into other modules, to achieve the reuse of functionality.

3, how to use the module?
3.1. Import
Instance file: spam.py, file name: spam.py, module name: Spam

#spam. Pyprint (' from the spam.py ') Money=1000def read1 (): Print (' Spam->read1 ', Money) def read2 (): Print (' Spam->re Ad2 ') read1 () def Change (): Global #声明为全局名称空间 money=0 #重新给money赋值

3.1.1, modules can contain executable statements and definitions of functions that are intended to initialize modules only if the module name is first encountered importing import statements
Import statements can be used anywhere in the program, and for the same module is import multiple times, in order to prevent you to repeat the import, Python optimization means: The first import after the module name loaded into memory, The subsequent import statement only adds a reference to the module object that has loaded the large memory, and does not re-execute the statements within the module as follows:

Import spam #只在第一次导入时才执行spam. py inside the code, the explicit effect here is to print only one, import spam #次 ' from the spam.py ', of course, the other top-level code is also executed, but not show the effect. Import Spamimport spam

Execution Result:

From the spam.py

We can find the module that is currently loaded from Sys.module, Sys.module is a dictionary that contains the mapping of the module name to the module object, which determines whether the import module needs to be re-imported.
3.1.2, each module is a separate namespace, defined in this module of the function, the namespace of the module as the global namespace, so that when we write our own module, we do not have to worry about our own module in the definition of global variables will be imported, and the user's global variables conflict.
#测试一: Money does not conflict with Spam.money

Import Spammoney = 123123print (Spam.money)-execution result: from the spam.py1000# Test two: Read1 and Spam.read1 do not conflict import spamdef Read1 (): PR Int ("---------->") spam.read1 ()

Execution Result:

From the Spam.pyspam->read1 1000
#测试三: Global variable that performs the Spam.change () operation money is still the import in spam Spammoney = 999spam.change () #更改的是spam里的moneyprint (Money)

Execution Result:

From the spam.py999

3.1.3, Summary:
Three things to do when importing module spam for the first time:
First thing: Create a namespace to hold the name defined in the spam.py;
Second thing: Execute spam.py based on the namespace you just created;
The third thing: Create a name spam point to the namespace, spam. The operation of the name, is based on spam.py.

3.1.4, alias for module name, equivalent to M1=1;M2=M1

Import spam as Smprint (Sm.money)

The way you alias an imported module is useful for writing extensible code, assuming there are two modules xmlreader.py and csvreader.py that define function read_data (filename): Used to read some data from a file, However, different input formats are used. You can write code to selectively pick the read module, for example:

if File_format = = ' xml ': Import xmlreader as Readerelif File_format = = ' csv ': Import Csvreader as Readerdata=reader. Read_date (filename)

3.1.5, importing multiple modules on a single line

Import Os,sys,re

3.2. From ... import ...
3.2.1, comparing import spam, will bring the source file's namespace ' spam ' to the current namespace, and must be spam when used. The way the FROM statement is equivalent to import, and a new namespace is created. However, the names in the spam are imported directly into the current namespace, and the name is used directly in the current namespace.
From spam import read1,read2
This way, it is good to use READ1 and read2 directly at the current location, while executing, still with the spam.py file global namespace
Test One: Import the function read1, still go back to spam.py in search of the global variable money

#test. Pyfrom spam import read1read1 () execution result: from the Spam.pyspam->read1 1000


Test Two: Import function read2, call READ1 () when executing, still return to spam.py for Read1 ()

#test. Pyfrom Spam import Read2def read1 (): Print (' ========== ') read2 ()

Execution Result:

From the Spam.pyspam->read2spam->read1 1000

Test three: The imported function read1 is overwritten by the read1 defined by the current location.

#test. Pyfrom Spam import Read1def read1 (): Print ("===========>") read1 () #重名时, overwrites the imported name

Execution Result:

From the spam.py===========>

One particular point to note is that variable assignment in Python is not a storage operation, but a binding relationship, as follows:

From spam import Money,read1money = 999 #将当前位置的名字money绑定到了999print (Money) #打印当前的名字read1 () #调用spam. PY name Money, still 1000

Execution Result:

From the Spam.py999spam->read1 1000

3.2.2, also supports as

From spam import read1 as read


3.2.3, also supports importing multiple lines

From spam import (MONEY,READ1,READ2)

3.2.4, from spam import * imports all names in spam that are not the beginning of the underscore (_) to the current location, and in most cases our Python program should not use this type of import, because "*" you do not know what name you import, It is likely that you will overwrite the name you have defined before. And very poor readability, no problem when importing in an interactive environment.

From spam import * #将模块spam中所有的名字都导入到当前名称空间print (Money) print (read1) print (read2) print (change)

Execution Result:

From the Spam.py1000<function read1 at 0x00000000028ca9d8><function read2 at 0x00000000028ca950>< function Change at 0x00000000028caa60>

can use __all__ to control * (to release the new version)
Add a line to the spam.py
__all__=[' money ', ' read1 '] #这样在另外一个文件中用from spam import * This can be imported in the list of the two names specified, not in the table cannot be called
3.2.5, for performance reasons, each module is imported only once, into the dictionary sys.modules, if you change the contents of the module, you must restart the program, Python does not support reloading or uninstalling the previously imported modules. Some students may think of removing a module directly from the Sys.modules can not be uninstalled, note that you deleted the Sys.modules module object may still be referenced by other program components, so it will not be clear. In particular, we refer to a class in this module, which produces many objects with this class, so that these objects have references to this module.
3.3, the module as a script execution
We can view the module name through the global variable __name__ of the module:
Run as script:

__name__ equals ' __main__ '

Import as module:

__name__=

Function: Used to control the. py file to perform different logic in different scenarios

if __name__ = = ' __main__ ':p rint (__name__) #被当成脚本文件执行时if __name__ = = ' __main__ ': print ("Now executed as script")

Execution Result:

__main__

This is done as a script.
When the module is imported:

Import spam

#当导入模块时, the module will be executed, the module has two printing effect, at this time spam not as a script run, so, will not execute the following code.
Execution Result:

Spam #打印了模块名

3.4. Module Search Path
The Python interpreter automatically loads some modules at startup, and you can use Sys.modules to view that when you first import a module (such as spam), you first check that the module has been loaded into memory (the memory that corresponds to the namespace of the currently executing file). If there is a direct reference, if not, the interpreter looks for the built-in module with the same name, and then looks for the spam.py file from the list of directories given by Sys.path if it is not already found.
So the search order of the summary module is:
Modules that have been loaded in memory---> Built-in modules--->sys.path paths
It is important to note that our custom module names should not be the same as the system's built-in modules. Although it is said every time, there will still be people who make mistakes.
After initialization, the Python program can modify the Sys.path, and the path is placed prior to the standard library being loaded.

Import syssys.path.append ('/a/b/c/d ') sys.path.insert (0, '/x/y/z ') #排在前的目录, preferred to be searched

Note: The search is based on the left-to-right order in Sys.path, the first priority is found, the Sys.path may also contain. zip archive files and. egg files, and Python will treat. zip archives as a directory.
#首先制作归档文件: Zip module.zip foo.py bar.py

Import syssys.path.append (' Module.zip ') import Foo,bar

#也可以使用zip中目录结构的具体位置
Sys.path.append (' Module.zip/lib/python ')
As for the. Egg file is a package created by Setuptools, which is a common format used in accordance with third-party Python libraries and extensions, and. Egg files are really just. zip files that add additional metadata such as version numbers, dependencies, and so on.
One thing to emphasize is that you can only import. py,.pyc files from a. zip file. Shared libraries and extension blocks written using C cannot be loaded directly from the. zip file (at this point the packaging system such as setuptools can sometimes provide a workaround), and loading files from. zip does not create. pyc or. pyo files, so be sure to create them beforehand to avoid loading modules that are degraded by performance.

3.5. Compiling Python files
In order to increase the load speed of the module, Python caches the compiled version, each module in the __pycache__ The directory is named MODULE.VERSION.PYC, usually containing the Python version number, as in CPython version 3.6, the compiled version of spam.py will be cached as __pycache__/ SPAM.CPYTHON-36.PYC, this naming convention allows for different versions, and different versions of Python authoring modules coexist.
Python checks that the modification time of the source file is compared to the compiled version and needs to be recompiled if it expires. This is a completely automated process. And the compiled module is platform independent, so the same library can be shared between different architectures of the system, that is, PYc makes a cross-platform bytecode, similar to Java fire. NET, is executed by Python virtual machine, but the content of PYC is related to Python version, Different versions of the compiled PYC file, the 2.5 compiled PYC file cannot be executed on 3.6, and the PYc file can be recompiled, so it appears only to increase the load speed of the module.
Tips:
1, the module name is case-sensitive, foo.py and foo.py represent two modules;
2, you can use the-O or-oo to convert the Python command to reduce the size of the compilation module;
3.6. Standard module
Python provides a library of standard modules that are built into the interpreter, which provides access to operations that are not part of the core of the language, but they are built-in, whether for efficiency or to provide access to the operating system primitives. These collection of modules are configuration items that rely on the underlying platform, such as the WinReg module only for Windows systems. It is particularly important to note that the SYS module is built into every Python interpreter
Sys.ps1
Sys.ps2
These two are valid only on the command line, and the result is that the interpreter is identified in interactive mode.
The variable sys.path is a list of strings that determines the path of the module search, initializes the default path from the environment variable Pythonoath, and initializes the value from the built-in if Pythonpath is not set, and we can modify it

Sys.path.append:import Osos.path.normpath (path) #规范化路径, convert the case and slash a= '/users/jieli/test1/\\\a1/\\\\aa.py/of Path. /..‘ Print (Os.path.normpath (a))

Printing results:

\users\jieli\test1

#具体应用

Import Os,syspossible_topdir = Os.path.normpath (Os.path.join (Os.path.abspath (__file__), Os.pardir, #上一级 Os.pardi R, Os.pardir)) Sys.path.insert (0,possible_topdir)

3.7. Dir () function
The built-in function dir is used to find the name defined in the module, returning an ordered list of strings

Import spamdir (spam)

If there are no parameters, dir () lists the name of the current definition
Dir () does not enumerate the names of the built-in functions or variables, they are defined in the standard module builtin, and can be enumerated,

Import Builtinsdir (Builtins)

This article is from the "Hyun-dimensional" blog, please be sure to keep this source http://xuanwei.blog.51cto.com/11489734/1953467

Python automated Transport Koriyuki module and package usage

Related Article

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.