目的不必多說:提高項目可讀性、可維護性 軟體目錄結構示例: Game/ |-- bin/ | |-- game.py | |-- core/ | |-- tests/ | | |-- __init__.py | | |-- test_main.py | | | |-- __init__.py | | ...
目的不必多說:提高項目可讀性、可維護性
軟體目錄結構示例:
Game/ |-- bin/ | |-- game.py | |-- core/ | |-- tests/ | | |-- __init__.py | | |-- test_main.py | | | |-- __init__.py | |-- main.py | |-- logs/ | |-- err.log | |-- run.log | |-- conf/ | |-- setting.py | |-- abc.rst | |-- setup.py |-- requirements.txt |-- README
那麼問題來了,當類似於如上的目錄結構時,我怎麼在game.py中去調用setting.py或者main.py中的函數呢???
解(有解給2分):
首先,需要通過os.path.abspath(__file__)獲取到game.py的絕對路徑,進而方便找到setting.py文件的位置
然後,再通過os.path.dirname()方法回到文件的父級目錄以及更上級的目錄
最後,將項目的絕對路徑通過sys.path.append()添加到系統環境變數中
此時,就可以調用啦,上慄子(真香!!!)
setting.py
1 def Aset(): 2 print("這裡是配置")
main.py
1 def hello(name): 2 print("hello,%s,這裡是主函數" % name)
game.py
1 import os 2 import sys 3 4 print(os.path.abspath(__file__)) 5 print(os.path.dirname(os.path.abspath(__file__))) 6 print(os.path.dirname(os.path.dirname(os.path.abspath(__file__)))) 7 BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) 8 sys.path.append(BASE_DIR) 9 10 from conf import setting 11 from core import main 12 13 setting.Aset() 14 main.hello("tj") 15 16 >>> 17 F:\Python\資料\第二次學習\study\week4\day06\Game\bin\game.py 18 F:\Python\資料\第二次學習\study\week4\day06\Game\bin 19 F:\Python\資料\第二次學習\study\week4\day06\Game 20 這裡是配置 21 hello,tj,這裡是主函數