命令列執行.py檔案報錯ModuleNotFoundError: No module named ‘...’
阿新 • • 發佈:2021-01-15
技術標籤:python
問題:
在pycharm終端執行python指令碼:python main.py
指令碼在匯入自定義模組或包時報錯:ModuleNotFoundError: No module named ‘…’
原因
參考:
https://blog.csdn.net/qq_36829091/article/details/82180866
解決方案
在報錯的模組中加入專案根路徑。
比如,如下的目錄結構:
可在main檔案中獲取專案根路徑,將root_path傳給報錯模組:
import os
root_path = os.path.abspath(os.path.dirname(__file__) )
file_path='報錯模組路徑'
cmd = f'python {file_path} {root_path}'
os.system(cmd)
在報錯模組中接收專案根路徑
import sys
rootPath = sys.argv[1]
sys.path.append(rootPath)
即可解決問題。
無論用什麼方式,核心就是在報錯模組中,匯入自定義模組之前執行:sys.path.append(rootPath) #rootPath是專案的根路徑