[英]How to import package in bash without ModuleNotFoundError
I had an error 'ModuleNotFoundError' when I run python file in .sh file.当我在 .sh 文件中运行 python 文件时出现错误“ModuleNotFoundError”。
First this is directory structure.首先这是目录结构。
- my_project/
--- common_lib/
----- __init__.py
----- my_module.py
--- dir_1/
----- test.py
----- test.sh
And this is contents of each file.这是每个文件的内容。
common_lib/ init .py common_lib/ init .py
def test_func():
print(1)
common_lib/my_module.py common_lib/my_module.py
def module_func():
print("This is module.")
dir_1/test.py dir_1/test.py
import common_lib as cl
cl.test_func()
dir_1/test.sh dir_1/test.sh
#!/usr/bin/env bash
python test.py
When I run test.py file directly using editor such as 'vs code' or 'pycharm', I got the right result '1'.当我直接使用诸如“vs code”或“pycharm”之类的编辑器运行test.py文件时,我得到了正确的结果“1”。 But when I run test.sh file, I got the following error.但是当我运行 test.sh 文件时,出现以下错误。
ModuleNotFoundError: No module named 'common_lib' ModuleNotFoundError: 没有名为“common_lib”的模块
How can I import python package without 'No module Error' in this case?在这种情况下,如何在没有“无模块错误”的情况下导入 python 包?
Place an (empty) __init__.py
into your package root as well as all subdirectories.将(空的) __init__.py
放入包根目录以及所有子目录中。 Then you can call the script as a module out of dir_1
:然后,您可以将脚本作为dir_1
的模块dir_1
:
.
├── __init__.py
├── common_lib
│ └── __init__.py
└── dir_1
├── __init__.py
├── test.py
└── test.sh
test.sh:测试.sh:
#!/usr/bin/env bash
cd .. && python -m dir_1.test
Output:输出:
./test.sh
1
Have a look at the Packages-docs for more details.有关更多详细信息,请查看Packages-docs 。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.