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 |
import sys sys.path.append( ".." ) import mod1 import mod2.mod2 |
Import imports of Python in the upper level directory module and the problem of recycling import solution