[英]Import module from parent folder but still working in child directory
我對 Python 比較陌生,我需要制作一個可以從父文件夾中的文件調用函數的腳本。 簡單來說,目錄現在看起來像這樣:
parentModule.py 包含以下腳本
def runFunction():
print('function triggered')
return 1
childScript.py 包含以下腳本
import sys, os
sys.path.append( os.path.dirname(os.path.realpath(__file__))+'/..')
import parentModule
def runChildMain():
'''
run runFunction from parentModule.py
'''
parentModule.runFunction()
# Do stuff in childDirectory, for example, create an empty python file
open('test', 'a').close()
runChildMain()
我需要能夠自己運行 childScript.py,因為稍后 childScript.py 將作為子進程運行。 問題是,當我使用之前沒有提到的 sys.path 時,使用 open() 創建文件的命令在父目錄中運行,而不是在子目錄中。 因此,這會導致在 parentDirectory 中創建文件“test”,但我需要在 childDirectory 中創建它。
我知道可以進入一個目錄,即:
父模塊.py:
from childDirectory.childScript import runChildMain
def runFunction():
runChildMain()
runFunction()
childScript.py
def runChildMain():
print("HIT Run child main")
if __name__ == "__main__":
runChildMain()
如果必須以這種方式設置文件結構,盡管您可能必須使用:
sys.path.append( os.path.dirname(os.path.realpath(__file__))+'/..')
所以我找到了解決方案。 基本上在導入父模塊之后,我需要將工作目錄更改為子目錄,以便繼續在子目錄中進行操作。
下面的代碼是我的問題的答案
# Import from parent directory -- https://stackoverflow.com/questions/67631/how-do-i-import-a-module-given-the-full-path?rq=1
import importlib.util
import sys, os
spec = importlib.util.spec_from_file_location("parentModule", "parentModule.py")
foo = importlib.util.module_from_spec(spec)
sys.modules["module.name"] = foo
spec.loader.exec_module(foo)
# Change working directory to child directory
os.chdir("childDir")
def runChildMain():
foo.runFunction()
# This will be executed in the child directory
open('test2', 'a').close()
runChildMain()
執行此操作的正確方法是使用 -m 開關運行腳本
python -m childDirectory.childScript # from the parent of childDirectory
然后在 childScript 中執行簡單from parentModule import runFunction
。 破解 sys 路徑是不好的做法,也應該避免使用 chdir(導致令人討厭的意外)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.