如何在没有 ModuleNotFoundError 的情况下导入 bash 中的包
How to import package in bash without ModuleNotFoundError
当我在 .sh 文件中 运行 python 文件时出现错误 'ModuleNotFoundError'。
首先这是目录结构。
- my_project/
--- common_lib/
----- __init__.py
----- my_module.py
--- dir_1/
----- test.py
----- test.sh
这是每个文件的内容。
common_lib/init.py
def test_func():
print(1)
common_lib/my_module.py
def module_func():
print("This is module.")
dir_1/test.py
import common_lib as cl
cl.test_func()
dir_1/test.sh
#!/usr/bin/env bash
python test.py
当我 运行 test.py 文件直接使用 'vs code' 或 'pycharm' 等编辑器时,我得到了正确的结果'1'。
但是当我 运行 test.sh 文件时,出现以下错误。
ModuleNotFoundError: No module named 'common_lib'
在这种情况下,如何在没有 'No module Error' 的情况下导入 python 包?
将一个(空的)__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
查看 Packages-docs 了解更多详情。
当我在 .sh 文件中 运行 python 文件时出现错误 'ModuleNotFoundError'。
首先这是目录结构。
- my_project/
--- common_lib/
----- __init__.py
----- my_module.py
--- dir_1/
----- test.py
----- test.sh
这是每个文件的内容。
common_lib/init.py
def test_func():
print(1)
common_lib/my_module.py
def module_func():
print("This is module.")
dir_1/test.py
import common_lib as cl
cl.test_func()
dir_1/test.sh
#!/usr/bin/env bash
python test.py
当我 运行 test.py 文件直接使用 'vs code' 或 'pycharm' 等编辑器时,我得到了正确的结果'1'。 但是当我 运行 test.sh 文件时,出现以下错误。
ModuleNotFoundError: No module named 'common_lib'
在这种情况下,如何在没有 'No module Error' 的情况下导入 python 包?
将一个(空的)__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
查看 Packages-docs 了解更多详情。