目的不必多說:提高專案可讀性、可維護性
軟體目錄結構示例:
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,這里是主函式
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/137146.html
標籤:Python
上一篇:Python--序列化與反序列化
