當我在 .sh 文件中運行 python 文件時,出現錯誤“ModuleNotFoundError”。首先這是目錄結構。- my_project/--- common_lib/----- __init__.py----- my_module.py--- dir_1/----- test.py----- test.sh這是每個文件的內容。common_lib/初始化.pydef test_func(): print(1)common_lib/my_module.pydef module_func(): print("This is module.")dir_1/test.pyimport common_lib as clcl.test_func()dir_1/test.sh#!/usr/bin/env bashpython test.py當我使用“vs code”或“pycharm”等編輯器直接運行test.py文件時,我得到了正確的結果“1”。但是當我運行 test.sh 文件時,出現以下錯誤。ModuleNotFoundError:沒有名為“common_lib”的模塊在這種情況下,如何導入 python 包而不出現“無模塊錯誤”?
1 回答
阿晨1998
TA貢獻2037條經驗 獲得超6個贊
將(空)__init__.py放入包根目錄以及所有子目錄中。然后您可以將腳本作為模塊調用dir_1:
.
├── __init__.py
├── common_lib
│? ?└── __init__.py
└── dir_1
? ? ├── __init__.py
? ? ├── test.py
? ? └── test.sh
test.sh:
#!/usr/bin/env bash
cd .. && python -m dir_1.test
輸出:
./test.sh
1
添加回答
舉報
0/150
提交
取消
