Python Basics-3 Package Introduction, syntax

Source: Internet
Author: User
Tags macbook

What is a module?

In the development of computer programs, as the program code more and more, in a file code will be more and more long, more and more difficult to maintain.

In order to write maintainable code, we grouped many functions into separate files so that each file contained relatively few code, and many programming languages used this way of organizing code. In Python, a. py file is called a module.

What are the benefits of using modules?
    1. The greatest benefit is that the maintainability of the code is greatly improved. Second, writing code does not have to start from scratch. When a module is written, it can be referenced elsewhere. When we write programs, we often refer to other modules, including Python built-in modules and modules from third parties.
    2. The use of modules also avoids conflicting function names and variable names. Each module has a separate namespace, so functions and variables of the same name can exist in separate modules, so we do not have to think about names that conflict with other modules when we write our own modules.
Module classification

The modules are divided into three types:

    • Built-in standard module (also known as standard library) execution help (' modules ') View all Python-included modules list
    • Third-party open source modules can be installed via the PIP Install Module name Network
    • Custom Modules
module invocation
Import Module  from Import xx  from Import xx as rename    from Import *

Note: Once the module is called, it is equivalent to executing the code in another py file

Custom Modules

This is the simplest, create a. py file, you can call it a module, you can import in another program

Module Lookup Path

found that their own module can only be used in the current path of the program can be imported, a directory and then import their own module on the error said can not find, this is why?

This is related to the import path

Import SYS Print (Sys.path)

Output

["'/library/frameworks/python.framework/versions/3.6/lib/python36.zip'  '/library/frameworks/python.framework/versions/3.6/lib/python3.6 '  ' /library/frameworks/python.framework/versions/3.6/lib/python3.6/lib-dynload '  '/library/frameworks/python.framework/versions/3.6/lib/python3.6/site-packages  ']

The Python interpreter will follow the list order to go to each directory to match the module name you want to import, as long as it matches the module name in a directory, import it immediately, and no longer look back.

Note that the first element of the list is empty, which represents the current directory, so your own defined module will be imported first in the current directory.

Open source module installation, use

Https://pypi.python.org/pypi is the open source module Library of Python, which, as of 2017 9.30, contains 118,170 modules from Python developers around the world, covering almost anything you want to do with Python. In fact, every Python developer can upload your own module to this platform just by registering an account, so developers around the world can easily download and use your module. So how do I download code from this platform?

1. Directly on the above page point download, download, unzip and enter the directory, execute the following command to complete the installation

Compiled source    python setup.py build installation source    python setup.py install

    1. Install directly from PIP
# Parmiko is the module name

The PIP command automatically downloads the module package and completes the installation.

The software is typically automatically installed in this subdirectory of your Python installation directory

/your_python_install_path/3.6/lib/python3.6/site-packages

PIP command By default will be connected to the foreign official Python server download, slow, you can also use the domestic watercress source, the data will be regularly synchronized foreign official website, a lot faster

sudo pip install-i http://pypi.douban.com/simple/alex_sayhi--trusted-host pypi.douban.com   #alex_ Sayhi is the module name
Use

After downloading, direct import use can, with the module call method is not poor, to demonstrate a connection to the Linux execution command module

#Coding:utf-8ImportParamikossh=Paramiko. Sshclient () Ssh.set_missing_host_key_policy (Paramiko. Autoaddpolicy ()) Ssh.connect ('192.168.1.108', 22,'Alex','123') stdin, stdout, stderr= Ssh.exec_command ('DF')Print(Stdout.read ()) ssh.close ();
< Span class= "token string" > < Span class= "token punctuation" >< Span class= "token punctuation" > Execute command -connect to server by username and password         
Packages (Package)

When your module files are more and more, you need to partition the module files, such as the responsible for interacting with the database to put a folder, the page interaction related to a folder,

. └──my_proj     # Code Catalog     │   ├──admin.py    │   ├──apps.py    │   ├──models.py    │   ├──tests.py    │   └──views.py    ├──manage.py    # configuration file directory         ├──settings.py        ├──urls.py        └──wsgi.py

Like the above, a folder to manage multiple module files, this folder is called a package

What about the modules between the different packages?

crm/views.py content def  sayhi ():    print('Hello world! ')

Call through manage.py

 from Import Viewsviews.sayhi ()

Execute manage.py (note here with Python2)

alexs-macbook-pro:my_proj alex$ lscrm        manage.py    my_projalexs-macbook-pro:my_proj alex$ python manage.py Traceback (most  recent):'manage.py' in <module > from    import  viewsimporterror:no module named CRM

Can't find the module, why?

A package is a folder, but a __init__.py file must exist under the folder, and the contents of the file can be empty. __int__.py is used to identify the current folder as a package.

Create an empty file in the CRM directory __int__.py, and then do it again.

Alexs-macbook-pro:my_proj alex$ Touch crm/__init__# Create an empty file alexs-macbook-pro:my_ Proj alex$ alexs-macbook-pro:my_proj alex$ ls crm/__init__. py    admin.py    models.py    views.py__pycache__    apps.py        tests.py    views.pycalexs-macbook-Pro: My_proj alex$ python manage.py Hello world!

Note that in Python3, even if the directory does not have __int__.py files can be created successfully, guess should be caused by the interpreter optimization, but create the package or remember to add this file.

Cross-module Import

The directory structure is as follows

__init__ . py├──crm│    __init__ . py│   ├──admin.py│   ├──apps.py│   ├──models.py│   ├──tests.py│   ├──views.py  ├── manage.py   └──proj    __init__. py    ├──settings.py    ├──urls.py    └── wsgi.py

Based on the above structure, how to implement in the crm/views.py import proj/settings.py module?

Direct import words, will error, said to find not module

$ python3 Views.pytraceback (most recent call last):   " views.py "  in <module> from    import'proj'

Because the path cannot be found, proj/settings.py is equivalent to the son (settings.py) of the brother (Proj) of Crm/views.py's father (CRM), settings.py is views.py cousin, in views.py can only import the same level Brother module code, or sub-level package module, do not know cousin Cousin's existence. What can I do about it?

The answer is to add an environment variable and add the father-level path to the Sys.path, so the import is equivalent to starting from the father level to find the module.

Adding environment variables in crm/views.py

Import= Os.path.dirname (Os.path.dirname (Os.path.abspath (__file__#__file__ is to print the module that is currently being executed. py file relative path, note is relative path print(base_dir) sys.path.append (  base_dir)from Import Settings def Sayhi ():     Print ('Hello world! ' )print(settings. DATABASES)

Output

$ python3 views.py/packages/my_proj---My proj init---  #proj/__init__.py Output inch # proj/settings.py Output {'host''localhost'}
* Note: Is it a problem to write the import URLs in proj/settings.py at this time?
databases= {    'host':'localhost'} Import URLs  #print('inproj/settings.py '  'URLs'

Why is it? Because now the program entrance is views.py, you settings.py import URLs, in fact, the equivalent in the CRM directory to find urls.py, rather than Proj directory, if you want to import the normal, to change to the following

databases= {    'host':'localhost'}  from Import URLs  #proj This level of directory has been added to the Sys.path, you can directly find print(' In proj/settings.py ')
Absolute Import & Relative Import

CD can be used in Linux. Go back to the previous level directory, CD. /.. On the 2 floor, this one. Refers to the relative path, in Python, the import can also be..

For example:

__init__ . py├──crm│    __init__ . py│   ├──admin.py│   ├──apps.py│   ├──models.py│   ├──tests.py│   ├──views.py  #  ├──manage.py   └──proj    __init__. py    #  From . Import URLs       ├──urls.py    └──wsgi.py

views.py Code

 from Import Settings def Sayhi ():     Print ('Hello world! ' )print(settings. DATABASES)

The result of the execution is error

" my_proj/crm/views.py " inch  from Import  'notimport

Or someone will see this mistake.

import beyond top-level package

In fact, the reasons for these two errors are the same: when it comes to relative imports, the folder corresponding to the package must be correctly viewed by the Python interpreter as a package, not as a normal folder. Otherwise, the relative import of a package in Python cannot be achieved by using the nested relationship between packages because it is not considered as a pack.

The folder is considered as a package by the Python interpreter to meet two criteria:

    1. The __init__.py file must be in the folder, and the file can be empty, but the file must exist.
    2. You cannot execute a PY file in the folder as a top-level module (that is, it cannot be used as a portal for the main function).

So the solution to this problem is that since you are performing a relative import in the views.py, do not use views.py as an entry procedure, and you can call views.py at the previous level manage.py

__init__ . py├──crm│    __init__ . py│   ├──admin.py│   ├──apps.py│   ├──models.py│   ├──tests.py│   ├──views.py  #   ├──manage.py  #└──proj    __init__. py     # From . Import URLs       ├──urls.py    └──wsgi.py

It turns out it's still not working, error.

import beyond top-level package

But after the change to the from ..proj import settings from . import models implementation of success, why?

from .. import modelsThe reason for the error is that this code will see the manage.py layer as the package, but in fact it is not, because the package can not be the top entry code, if you want to do not go wrong, you can only move the manage.py up another layer.

The correct code directory structure is as follows

  packages/    __init__. py    #frommy_proj.crm  import views     └──my_proj        ├──crm        │   ├──admin.py        │   ├──apps.py        │   ├──models.py        │   ├──tests.py        │   ├──views.py  #from. Import models;           └──proj            __init__. py            ├──settings.py            ├──urls.py            └──wsgi.py 

The execution of manage.py will not be an error.

Note: Although Python supports relative import, it is not recommended to use it frequently in projects where the path relationship between modules is more stringent and improper handling is error-prone.

Python Basics-3 Package introduction, Syntax

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.