Python module Additions

Source: Internet
Author: User

Python contains the module method in subdirectories is relatively simple, the key is to be able to find the path to the module file inside the Sys.path.
Here are some examples of common situations:

(1) The main program and the module program are in the same directory:

such as the following program structure:
'--src
|--mod1.py
'--test1.py

If the module mod1 is imported in the program test1.py, the import mod1 or from MOD1 import * is used directly;

(2) The directory where the main program resides is the parent (or grandparent) directory of the directory where the module resides

such as the following program structure:
'--src
|--mod1.py
|--MOD2
| '--mod2.py
'--test1.py

If you import the module mod2 in the program test1.py, you need to create an empty file __init__.py file in the Mod2 folder (you can also customize the Output module interface in the file); Then use the From MOD2.MOD2 Import * or import mod2.mod2.

(3) Main program import module in upper directory or other directory (peer)

such as the following program structure:
'--src
|--mod1.py
|--MOD2
| '--mod2.py
|--Sub
| '--test2.py
'--test1.py

If you import modules Mod1 and MOD2 in the program test2.py. You first need to create a __init__.py file (same (2)) under MOD2, and you do not have to create the file under SRC. Then call the following method:
The following program execution methods are executed in the directory where the program files are located, such as test2.py is on CD sub; then execute Python test2.py
While test1.py is on CD src, then execute Python test1.py; The success of Python sub/test2.py in the SRC directory is not guaranteed.
Import Sys
Sys.path.append ("..")
Import Mod1
Import MOD2.MOD2


(4) from (3) it can be seen that the key to the import module is able to find the path of the specific module according to the value of the SYS.PATH environment variable. Here are just a few of the top three simple scenarios.

From: http://hi.chinaunix.net/?253639/viewspace-25422

Python module Additions

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.