import os, sys, inspect# realpath() will make your script run, even if you symlink it :)cmd_folder = os.path.realpath(os.path.abspath(os.path.split(inspect.getfile( inspect.currentframe() ))[0]))if cmd_folder not in sys.path:sys.path.insert(0, cmd_folder)
# Use this if you want to include modules from a subfoldercmd_subfolder = os.path.realpath(os.path.abspath(os.path.join(os.path.split(inspect.getfile( inspect.currentframe() ))[0],"subfolder")))if cmd_subfolder not in sys.path:sys.path.insert(0, cmd_subfolder)
# Info:# cmd_folder = os.path.dirname(os.path.abspath(__file__)) # DO NOT USE __file__ !!!# __file__ fails if the script is called in different ways on Windows.# __file__ fails if someone does os.chdir() before.# sys.argv[0] also fails, because it doesn't not always contains the path.
import os, sysfrom subprocess import Popen, PIPEtry:path = Popen("find / -name 'file' -type f", shell=True, stdout=PIPE).stdout.read().splitlines()[0]if not sys.path.__contains__(path):sys.path.append(path)except IndexError:raise RuntimeError("You must have FILE to run this program!")
# /lib/my_module.py# /src/test.py
if __name__ == '__main__' and __package__ is None:sys.path.append(os.path.abspath(os.path.join(os.path.dirname(__file__), '../lib')))import my_module
from module_1 import func_1
def func_2():func_1()
if __name__ == '__main__':func_2()
你在cmd中运行python module_2.py,它将运行func_1()定义的内容。这通常是我们导入相同层次结构文件的方式。但是当你在module_2.py中写入from .module_1 import func_1时,python解释器会说No module named '__main__.module_1'; '__main__' is not a package。所以为了解决这个问题,我们只是保留我们刚刚做出的更改,并将两个模块移动到一个包中,并制作第三个模块作为调用者来运行module_2.py。
project\package_1\module_1.pymodule_2.pymain.py
main.py:
from package_1.module_2 import func_2
def func_3():func_2()
if __name__ == '__main__':func_3()
但是我们在module_2.py的module_1之前添加.的原因是,如果我们不这样做并运行main.py,python解释器会说No module named 'module_1',这有点棘手,module_1.py就在module_2.py旁边。现在我让module_1.py中的func_1()做一些事情: