Python import module method

Source: Internet
Author: User

PythonThe module method in the subdirectory is relatively simple. The key is to find the module path in SYS. Path.File.
The following describes several common cases:
(1) The main program and Module Program are in the same directory:
As shown in the following program structure:
'-- SRC
| -- Mod1.py
'-- Test1.py
If you import the module mod1 in the test1.py program, useImportMod1 or from mod1 import *;

(2) The main program directory is the parent (or ancestor) Directory of the module directory.
As shown in the following program structure:
'-- SRC
| -- Mod1.py
| -- Mod2
| '-- Mod2.py
'-- Test1.py
If you want to import the module mod2 to test1.py, create an empty file _ init _ in the mod2 folder __. py file (you can also customize the output module interface in this file), and then use from mod2.mod2 import * or import mod2.mod2.

(3) The main program imports modules in the upper-level directory or modules under other directories (Level level)
As shown in the following program structure:
'-- SRC
| -- Mod1.py
| -- Mod2
| '-- Mod2.py
| -- Sub
| '-- Test2.py
'-- Test1.py
If the program test2.py is used to import modules mod1 and mod2. First, create the _ init _. py file under mod2 (same as (2). SRC does not need to create this file. The call method is as follows:
The following program execution methods are all executed in the directory where the program file is located. For example, test2.py is executed in CD sub, and then Python test2.py is executed.
While test1.py runs Python test1.py after cd src; it does not guarantee that python sub/test2.py is successfully executed in the src directory.
Import sys
SYS. Path. append ("..")
Import mod1
Import mod2.mod2

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.