import syssys.path.insert(0, r'/from/root/directory/application')
from application.app.folder.file import func_name ## You can also use '*' wildcard to import all the functions in file.py file.func_name()
import systry:# The insertion index should be 1 because index 0 is this filesys.path.insert(1, '/absolute/path/to/folder/a') # the type of path is string# because the system path already have the absolute path to folder a# so it can recognize file_a.py while searchingfrom file_a import Aexcept (ModuleNotFoundError, ImportError) as e:print("{} fileure".format(type(e)))else:print("Import succeeded")
#2安装你的包
一旦你安装了你的应用程序(在这篇文章中,安装教程不包括在内)
你可以简单地
try:from __future__ import absolute_import# now it can reach class A of file_a.py in folder a# by relative importfrom ..a.file_a import Aexcept (ModuleNotFoundError, ImportError) as e:print("{} fileure".format(type(e)))else:print("Import succeeded")
package/||----- __init__.py (Empty file)|------- main_module.py (Contains: import subpackage_1.module_1)|------- module_0.py (Contains: print('module_0 at parent directory, is imported'))|||------- subpackage_1/| || |----- __init__.py (Empty file)| |----- module_1.py (Contains: print('importing other modules from module_1...')| | import module_0| | import subpackage_2.module_2| | import subpackage_1.sub_subpackage_3.module_3)| |----- photo.png| || || |----- sub_subpackage_3/| || |----- __init__.py (Empty file)| |----- module_3.py (Contains: print('module_3 at sub directory, is imported'))||------- subpackage_2/| || |----- __init__.py (Empty file)| |----- module_2.py (Contains: print('module_2 at same level directory, is imported'))
现在运行main_module.py
的输出是
>>>'importing other modules from module_1...''module_0 at parent directory, is imported''module_2 at same level directory, is imported''module_3 at sub directory, is imported'