Brief introduction of python import modules in different paths

  • 2020-06-12 09:32:58
  • OfStack

python contains subdirectories of the module method is relatively simple, the key is to find the path to the module file in sys.path.

The following is a detailed introduction to some common situations:

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

As shown in the following program structure:

`-- src
|-- mod1.py
`-- test1.py

If the module mod1 is imported into program test1.ES20en, then import mod1 or from mod1 import * is directly used.

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

As shown in the following program structure:

`-- src
|-- mod1.py
|-- mod2
| `-- mod2.py
`-- test1.py

To import the module mod2 in the program test1.ES45en, create the empty file with the mod2 folder (you can also customize the output module interface in this file). Then use from mod2.es52EN2 import * or import ES55en2.mod2.

(3) The main program imports modules in the upper directory or modules under other directories (level)

As shown in the following program structure:

`-- src
|-- mod1.py
|-- mod2
| `-- mod2.py
|-- sub
| `-- test2.py
`-- test1.py

If you import the modules mod1 and mod2 in the program test2.ES79en. First, you need to establish the document (with (2)) under mod2, with no need to establish it under src. Then the invocation is as follows:

The following procedures are executed in the directory where the program files are located, such as test2.ES89en is in cd sub; Then execute python test2.py

test1.py is in cd src; python test1.ES103en; Success of python sub/ test2.ES108en under src is not guaranteed.

import sys
sys.path.append("..")
import mod1
import mod2.mod2

(4) It can be seen from (3) that the key to import module is to find the path of specific module according to the value of sys.path environment variable.

Here are just three simple cases.


Related articles: