PythonThe module method in the subdirectory is relatively simple. The key is to find the module path in SYS. Path.File.
The following describes several common cases:
(1) The main program and Module Program are in the same directory:
As shown in the following program structure:
'-- SRC
| -- Mod1.py
'-- Test1.py
If you import the module mod1 in the test1.py program, useImportMod1 or from mod1 import *;
(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 to test1.py, create an empty file _ init _ in the mod2 folder __. py file (you can also customize the output module interface in this file), and then use from mod2.mod2 import * or import mod2.mod2.
(3) The main program imports 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