Import mechanism for Python 2

Source: Internet
Author: User

http://blog.csdn.net/sirodeng/article/details/17095591 Python's import mechanism for forgetting:

In Python, each py file is called a module, and each directory with a __init__.py file is called a package. As long as the module or the directory in which the package resides is in Sys.path, you can use the Import module or the import package.

If you want to use code that is not in the current module, you need to use import, as we all know.
If you want to use the module (PY file) and the current module in the same directory, just import the corresponding file name, such as the use of b.py in a.py:
Import b
But what if you want to import a file of a different directory (for example, b.py)?
You first need to use the Sys.path.append method to add the directory where b.py resides in the search directory. Then import them, for example
Import Sys
Sys.path.append (' c:\xxxx\b.py ') # This example is for Windows users
In most cases, the above code works very well. But if you don't see any problem with the code above, it's important to note that the code above sometimes finds no module or package (Importerror:no module named XXXXXX), because:
The SYS module is written in C, so the string supports ' \ n ', ' \ R ', ' \ t ', and so on to represent special characters. So the above code is best written as:
Sys.path.append (' c:\\xxx\\b.py ')
or Sys.path.append (' c:/xxxx/b.py ')
This avoids invalid search directory (Sys.path) settings because of the incorrect composition of the escape character.

But the above method is for the script, each use to remember to add, if permanently add a directory into the Sys.path?

How do I add a path "permanent" to Sys.path?

Sys.path is the path set of the Python search module and is a list

You can use Sys.path.append (path) to add related paths in a Python environment, but the paths you add automatically disappear when you exit the Python environment!

You can use the following command to enter the search path for the current Python:

Python-c "Import Sys;print" current Python is: ' +sys.prefix;print ' \ n '. Join (Sys.path) "

Practice using the Sys.path.append method to add a path that shows that exiting Python will disappear!

Python-c "Import Sys;print" current Python is: ' +sys.prefix;sys.path.append (R ' E:\DjangoWord ');p rint ' \ n '. Join (Sys.path) "

Run again and you will find yourself adding the path E:\DjangoWord () does not exist!

Python-c "Import Sys;print" current Python is: ' +sys.prefix;print ' \ n '. Join (Sys.path) "

To solve this problem, the following methods can be used:


Place your own py file in the Site_packages directory:

The following command shows the Site-packages directory:

Python-c "from distutils.sysconfig import get_python_lib; Print Get_python_lib () "

However, this can lead to a problem, that is, the various types of modules placed in this folder, will lead to a disorderly problem, this is obvious.

Note that you do not create subfolders, and then place your own modules in subfolders to resolve the issue, which results in an error when using the import statement.


Using the PTH file, create the. pth file in the Site-packages file, write the path to the module, one line at a path, the following is an example, the PTH file can also use annotations:

#. pth file for the My project (this line is a comment)
E:\DjangoWord
E:\DjangoWord\mysite
E:\DjangoWord\mysite\polls

This is a good approach, but there are administrative issues and cannot be shared in different versions of Python.


Using the PYTHONPATH environment variable, enter the relevant path in this environment variable, with a comma between the different paths (in English!). ) Separately, if the Pythonpath variable does not already exist, you can create it! As shown in the following:

The paths here are automatically added to the Sys.path and can be shared in different versions of Python, which should be the more convenient way.

For information about the environment variables that are related to Python, refer to:

Http://docs.python.org/using/cmdline.html find Pythonpath on the page


The following is a description of the environment variable:

Pythonpath¶

Augment the default search path for module files. The format is the same asthe Shell's Path:one or more directory pathnames separated byos.pathsep (e.g. colons on Unix or semicolons on Windows). Non-existent directories is silently ignored.

In addition to normal directories, individual PYTHONPATH Entriesmay refer to zipfiles containing pure Python modules (in E Ither source orcompiled form). Extension modules cannot is imported from Zipfiles.

The default search path is installation dependent and generally begins withprefix/lib/pythonversion (see pythonhome above ). ITIS always appended to PYTHONPATH.

An additional directory would be inserted in the search path in front Ofpythonpath as described above underinterface option S. The search path can be manipulated Fromwithin a Python program as the variable Sys.path.

Attached: Various methods of Python installation module

1, self-written module, can be added directly to the path. This makes it possible to call directly.
Import Sys
Sys.path.append ("/home/username/")

2. Single File module
Copy files directly to $python_dir/lib

3, the third-party library downloaded on-line, after the general decompression, find setup.py file
Run Python setup.py install

4. Egg file
1) Download ez_setup.py, run Python ez_setup
2) Easy_install *.egg

5. Pip Installation method
Pip is a tool for installing the Python package, providing an installation package that lists the packages that have been installed, the upgrade package, and the ability to uninstall the package.
Pip is a replacement for Easy_install, which provides the same functionality for finding packages as Easy_install, so packages that can be installed using Easy_install can also be installed using PIP.
Install PIP
PIP installation can be via source code package, Easy_install or script.
Here are the various installation methods:
Source Code mode:
$ wget https://pypi.python.org/packages/source/p/pip/pip-1.2.1.tar.gz (replace with latest package)
$ tar xzf pip-1.2.1.tar.gz
$ CD pip-1.2.1.tar.gz
$ python setup.py Install
Easy_install:
$ easy_install pip
get_pip.py script:
$ curl-0 https://raw.github.com/pypa/pip/master/contrib/get-pip.py
$ sudo python get-pip.py
OK, here's a look at the use of PIP
Install the Package
$ pip Install Markdown
List the installed packages
$ pip Freeze
Install a specific version of the package
by using = =, >=, <=, <, specify a version number.
$ pip Install ' markdown<2.0 '
$ pip Install ' markdown>2.0,<2.0.3 '
Upgrade Package
Upgrade package to current latest version, can use-u or--upgrade
$ pip install-u Markdown
Uninstalling packages
$ pip Uninstall Markdown
Query Package
Pip Search "Markdown"

6, Special library installation (a Scientific computing library Enthought Python distribution installation)
Enthought Python distribution installed under Ubuntu Test, should be a netizen's request, asked how to install the library, from the official website downloaded a file
epd_free-7.3-2-rh5-x86.sh, cover file is sh format file, with sudo bash epd_free-7.3-2-rh5-x86.sh run this file, appear a lot of permission to read, point to enter, do not continuous point
Need to take a look at it, and finally appear a different one its copyright notice, enter "Yes", and then let the selection of the installation directory, click Enter, installed in the current directory.
So it's ready for installation.
Input under current directory
>>> Ipython--pylab
Just come out.
Python 2.7.3 (Default, APR 20 2012, 22:44:07)
Type "Copyright", "credits" or "license" for more information.
IPython 0.12.1--an enhanced Interactive Python.
? Introduction and overview of IPython ' s features.
%quickref, Quick Reference.
Help, Python ' s own Help system.
Object? Details about ' object ', use ' object? ' for extra details.
Welcome to Pylab, a matplotlib-based Python environment [Backend:tkagg].
For more information, type ' help (Pylab) '.
This is called again. The library doesn't need any further research because I can't use it at work.
In [1]: From scipy import *
In [2]: A=zeros (1000)
In 3]: a[:100]=1
In [4:b=fft (a)
In [5]: Plot (ABS (b))

REF:

Reason for not being able to import (Importerror:no module named * * * * * * *)

Http://hi.baidu.com/itaolei/item/197d9f10521ba8011894ec99

Some recent summary of Python learning: adding Paths to Sys.path

http://hi.baidu.com/billschen/item/9ee4aad4b5a9391d21e25016

Top
0
Step

Import mechanism for Python 2

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.