Basic Python (eight)--modules and packages

Source: Internet
Author: User

Security Code: Indifferent Childe


Modules in Python

Splitting a code-heavy program into multiple, independent, but interactive pieces of code that are self-contained, organized code snippets are Modules.

The module behaves as a code file that ends in. py in the physical form:

A file is considered a separate module, and a module can also be viewed as a file

The file name of the module is the name of the module plus the Extension. py

Each module has its own namespace

Python allows the "import" of other modules for code reuse, which also enables the organization of separate code files into larger program Systems:

In python, the module is also an object

All variables defined on the top level of a module are imported as properties of the module being imported

python program architecture:

A python program typically includes a top-level program file and other module files (0, one, or More)

Top-level files: contains the main control flow of the program

Module Files: provides a variety of functional components for top-level files or other modules

When the module is first imported (or overloaded), python immediately executes the top-level program code for the module file (code that is not inside the Function)

The code in the body of the function is not executed until the function is called

650) this.width=650; "src=" https://s4.51cto.com/wyfs02/M00/8C/7C/wKiom1ht4xSymysJAAC0DnOvXPc213.jpg "title=" Python program architecture. jpg "width=" "height=" 269 "border=" 0 "hspace=" 0 "vspace=" 0 "style=" width:700px;height:269px; "alt=" Wkiom1ht4xsymysjaac0dnovxpc213.jpg "/>

You can use Help (' modules ') to see what Python's Standard library modules are in the System.

The execution environment of the module:

Modules are imported, but modules can also import and use other modules, which can be written in Python or other programming languages

Modules can contain variables, functions, and classes to do their work, and functions and classes can include variables and other elements

650) this.width=650; "src=" http://s3.51cto.com/wyfs02/M01/8C/78/wKioL1ht5fKhKr5uAAB6yZNrhQ8676.jpg "title=" The execution environment of the Python module. jpg "width=" "height=" "border=" 0 "hspace=" 0 "vspace=" 0 "style=" width:700px;height:500px; "alt=" Wkiol1ht5fkhkr5uaab6yznrhq8676.jpg "/>

import module:

Only module names can be used when importing modules, not module filenames with. py suffixes

Import Statement: imports the specified entire module, including generating a namespace named after the module name

Import Module1 [, module2 [, ... modulen]]

It is recommended that an import statement import only one module

Import module as Module_alias

Once an alias is used, it can only be called with an alias

From-import statement: commonly used to import only some of the properties of a specified module to the current namespace

From module import name1 [, name2 [, ... namen]]

Import and From-import are assignment statements:

Import and from are executable statements, similar to def, so they can be nested in the If test, appear in def, and so On.

Python executes these statements before parsing them, which means that all properties from the module will be used only after the import statement is executed

Both import and from are implicit assignment statements:

Import assigns the entire module object to a variable name

From assigns one or more variable names to an object of the same name in the module that imports this module

The module is the Namespace:

The namespace of the module can be obtained through the attribute __dict__ or dir (M)

Module properties can be obtained by the dot (.) operator in the format m.attr

A module is a separate scope (local variables are global variables)

Import Working mechanism:

The import statement performs three steps when importing a specified module:

Locate the module file

Search for module files under the specified path

Compile into byte code

Files are compiled when they are imported, so the. PYc bytecode files for the top-level files are discarded after they are used internally

Only files that are imported will be left with The. PYc file

Executes the code of the module to create the object it defines

All statements in the module file are executed sequentially,

Any assignment to the variable name in this step will result in the properties of the resulting module file.

Note: The module does not perform the above steps until the first import:

Subsequent import operations are simply extracting the loaded module objects in memory

Reload () can be used to reload the module

The top level of the module executes and is Imported:

A module file can support both top-level execution (as a top-level file) or be imported (as a module file).

Each module has a built-in property named __name__, and Python automatically sets the property:

If the file is executed as a top-level program file, at startup, the value of __name__ is "__main__"

If it is imported, the value of __name__ is the module name

You can detect your own __name__ property in a module file, which allows you to run the specified code at execution time, often for self-testing of the Module.

#!/usr/bin/pythondef testFunc (): Print "Hello world" if __name__ = = "__main__": TestFunc ()

Module Search:

The Python interpreter must find the corresponding module file in the import module, and Python will look for the module file in the following directories:

The main directory of the program;

Pythonpath directory (if This variable is set);

Standard link library directory;

The contents of any. PTH file (if A. PTH file Exists)

These four components are combined to include the path that Sys.path contains, and Python chooses the first file in the search path that matches the import file name


Packages in Python

If we develop a series of modules for others to use, and these modules are related, if according to the previous said, to set the module search path, and then put this series of modules in, so it will be very troublesome, so there is the concept of the Package.

A package is used to merge a set of modules into a directory, which is a package, and the directory name is the package Name.

A package is a hierarchical file directory structure that defines a Python application execution environment consisting of modules and sub-packages

Based on the package, python can specify the Module's import path when executing the module import, such as:

Import Dir1.dir2.mod1

650) this.width=650; "src=" http://s1.51cto.com/wyfs02/M01/8C/79/wKioL1ht5-7TX6GAAAAfHjMIFds650.png "title=" Python module package. png "alt=" wkiol1ht5-7tx6gaaaafhjmifds650.png "/>

to use the package1, the Py_pkg_mod container must be in the module search path. Use the following command to Import:

Import Package1.mod1

The __init__.py file must be in each directory within the path of the package import statement:

__init__.py can contain Python code, but is usually empty;

A role that is used only to act as a hook for package initialization, to generate a module namespace for a catalog, and to implement the from * behavior when using catalog Import

To publish a Python module or program:

Python modules, extensions, and applications can be packaged and published in the following ways:

Compressing files (using the distutils module):

. tar.gz files for Windows Zip files and Unix-like platforms

Automatic unpacking or automatic installation of executable files:

. exe files in Windows

self-contained, Ready-to-run executable program that does not require installation:

. exe files for windows, zip compressed files with a small script prefix on unix,. app files on mac, etc.

Platform-related installers:

. msi files on windows,. rpm, src.rpm, and. Deb files that are common on linux;

Python eggs:

More popular Third-party Extensions

to publish a module using Distutils:

The Distutils module can help to complete the module or program Release.

"publish" refers to a collection of files that are federated together to build, package, and publish modules using Distutils

Create a good release for installation or upload to PyPI to share with others

Steps to create a publication:

1, The code files are organized into the module container;

2, prepare a readme or README.txt file;

3. Then create the setup.py file in the container , in the following format:

From Distutils.core import setupsetup (name = ' Testmod ', #包名 version = ' 0.0.1 ', author = ' Forgotten ', A Uthor_email = ' [email protected] ', py_modules = [' testmod '], #此包内所有的模块列表, Multiple module names separated by commas URL = ' Http://itchentao.blo g.51cto.com ', #模块可以从哪里获取到, Here's just a sample description = ' A simple module ', #模块的简要描述)

Common parameters of Setup.py:

Name: Names of packages (required)

Version: Revision number (required)

Author: Author name

Author_email: Author's E-mail Address

Maintainer: name of the maintainer

Maintainer_email: the Maintainer's e-mail address

Url: home page of the package

Description: A brief description of the package

Long_description: detailed description of the package

Download_url: download location of the package

Classifiers: string Classifier List

Py_modules: a list consisting of all module names (required)

These modules may be located in the root directory of the package (modulename) or in a sub-package directory (subpkg1.modulename)

Packages: a list of the name of each child package

Platforms: List of applicable platforms

License: License

The parameters of setup.py are broadly divided into two categories:

Meta-data information (name, version, and so On)

List of contents in the package (py_modules, packages, etc.)

4. Complete Packing:

Execute the "python setup.py sdist" command in the container directory to be published for source Packaging:

Sdist can be packaged by specifying the following format:--formats=

Zip:zip Compressed Files

gztar:tar.gz Compressed Files

bztar:tar.bz2 Compressed Files

Ztar:tar. Z Compressed Files

Tar:tar file

You can also run the "python setup.py bdist" command in the container directory you want to publish to package the binary release:

Bdist can be packaged by specifying the following format:--formats=

gztar:tar.gz Compressed Files

Ztar:tar. Z File

Tar:tar file

Zip:zip Compressed Files

RPM:RPM Package File

Pkgtool:solaris Pkgtool

Wininst:windows can self-extracting zip format package

Msi:microsoft Installer

Bdist_dump: a package made in tar, ztar, gztar, zip format

Bdist_rpm: packages made in RPM format

Bdist_wininst: a package made in wininst format

Bdist_msi: packages made in MSI format

How to get Help:

Python setup.py--help

Python setup.py--help-commands: All commands that can be used, such as Build,install

Python setup.py command--help: get help with specific commands

Python setup.py command--help-formats: get the format supported by a particular command

5, The installation of packaged modules:

Installing the source package file using the Python setup.py install command

Packages uploaded to PyPI can be installed using the Pip,easy_install command


Install the Third-party module package in Python:

Installing the module using the Python setup.py install command: There are two stages (build, Install)

If you do not execute the python setup.py build and execute the Python setup.py install directly, The build will be done automatically at the time of Installation.

When the Python setup.py build is executed, python creates a build directory under the directory where the command is Executed.

Python setup.py build:

--build-base=/path/to/build_dir the specified directory for Build,build is saved to the specified directory.

After the build is complete, the following directory will be generated in the build directory to save the module files that will be installed:

Lib: Save the module developed by the Pure Python language

Lib.platform: A compiled library file that is closely related to the platform and cannot be implemented across platforms

Python setup.py install:

The install process simply copies the compiled files to the specified module installation directory.

When the installation directory is not specified, it is installed by default in the Third-party module installation directory (/python installation directory/lib/site-packages)

Custom Installation Path:

--user=: install to a specific directory in the specified User's home directory

Commonly used for ordinary users, because the normal user has no write permission to some directories

--prefix=: Specify the installation path for the Python library

To have write access to the specified directory

--exec-prefix=: used to specify the installation path of a specific file that is not related to Python and that is implemented by other languages and that is relevant to the platform

To have write access to the specified directory

Deep customization:

--install-purelib=/path/to/python_lib

--install-platlib=/path/to/plat_lib

--install-lib=/path/to/lib

The--install-purelib and--install-platlib options can be replaced with--install-lib.

If all three options are specified, The--install-lib has the highest priority

--install-scripts=/path/to/bin Specify the installation path for the executable file

--install-data: Specify the installation path for the data file

--install-headers: Specifies the header file installation path for executable programs written in C

This article is from the "home" blog, please make sure to keep this source http://itchentao.blog.51cto.com/5168625/1889305

Basic Python (eight)--modules and packages

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.