Python import custom module methods

  • 2020-04-02 14:36:55
  • OfStack

Python contains module methods in subdirectories that are relatively simple, but the key is to be able to find the path to the module file in sys.path.

The following will specifically introduce several common cases:

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

As the following program structure:


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

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

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

As the following program structure:


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

      If you import module mod2 in program test1.py, you need to set up an empty file, s/s. Py, in the mod2 folder (you can also customize the output module interface). Then use from mod2. Mod2 import * or import mod2. Mod2.

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

As 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.py. The first step is to set up the.py file (same as (2)) under mod2. SRC does not have to set up the file. Then the method of invocation is as follows:

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

And test1.py is at CD SRC; Then execute python test1.py; Successful execution of python sub/test2.py in the SRC directory is not guaranteed.


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

  (4) as can be seen from (3), the key to importing a module is to be able to find the path of a specific module according to the value of the sys.path environment variable. Here are just three simple cases.

Comment on:

When running python interaction in the current directory of CMD under win, sys. path. Append (".. ") is also required if the current directory is a python package to introduce it in the current interaction. ), but my personal practice is usually sys.path.insert(0,".." )


c:/py25>cd sub 
c:/py25>python 
>>>#import sub # The hint is not found here  
>>>import sys 
>>>sys.path.insert(0,'..') # or sys.path.append("..") 
>>>import sub # Here we introduce success  

It looks like the snake's current list is "sons don't know fathers",

Sys. path.insert(0,'.. /.. ')...


Related articles: