Import imports of Python in the upper level directory module and the problem of recycling import solution

Source: Internet
Author: User

Third-party module packages are often used when writing programs using Python. This package can be installed via the Python setup install and imported via the import XXX or from xxx import yyy. However, if it is a self-written dependency package, and do not want to install to the corresponding Python directory, you can put in this directory for import to call, in order to clarify the relationship between the program, for example, we will put this package in the Lib directory and then call. This article summarizes the common module invocation methods.

One, the level of the directory of the tune has

The program structure is as follows:


--SRC
|--mod1.py
|--test1.py


If you import the module mod1 in the program test1.py, use the

Import Mod1
Or
From MOD1 import *;

Second, call the sub-directory module


The program structure is as follows:

--SRC
|--mod1.py
|--Lib
| |--mod2.py
|--test1.py


When you see the test1.py and Lib directories (that is, the parent directory of the mod2.py), if you want to import the module mod2.py in the program test1.py, you can create an empty file __init__.py file in the Lib folder (you can also customize the Output module interface in the file). Then use:

From LIB.MOD2 Import *
Or
Import Lib.mod2.


Third, call the file under the parent directory


The program structure is as follows:

--SRC
|--mod1.py
|--Lib
| |--mod2.py
|--Sub
| |--test2.py


Here want to implement test2.py call mod1.py and mod2.py, the practice is that we jump to the SRC directory, directly can call Mod1, and then build an empty file on the Lib __init__.py, can be like the second step to call the sub-directory module, The call was made via import lib.mod2. The specific code is as follows:

?
1234 importsyssys.path.append("..")import mod1importmod2.mod2

Import imports of Python in the upper level directory module and the problem of recycling import solution

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.