Python module import problems

Source: Internet
Author: User
The module method in the python sub-directory is relatively simple. The key is to find the path to the module File in SYS. Path. The following describes several common scenarios: (1) Master Program It is in the same directory as the Module Program, as shown in the following program structure: '-- SRC | -- Mod1.py '-- Test1.py If you import the module mod1 in the test1.py program, you can directly use import mod1 or from mod1import *;(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 in the test1.py program, you need to create an empty file _ init _. py in the mod2 folder (you can also customize the output module interface in this file ); Use the from mod2.mod2 import * or import mod2.mod2. (3) Main program to import 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.