[英]ModuleNotFoundError error when running script
I have examined many questions that have been asked before but I couldn't find a solution to my problem.我检查了许多以前提出的问题,但我找不到解决问题的方法。
I'm running python3 folder1/script1.py command on the terminal in the root directory but I get the error ModuleNotFoundError: No module named 'folder2' .我在根目录的终端上运行python3 folder1/script1.py命令,但出现错误ModuleNotFoundError: No module named 'folder2' 。 I added __ init __.py to the folders but still couldn't find a solution.
我将__ init __.py添加到文件夹中,但仍然找不到解决方案。
My project directory is like this:我的项目目录是这样的:
└── root
├── folder1
│ ├── script1.py
│
└── folder2
├── module1.py
module1.py:模块1.py:
def say_hello():
print('hello')
scipt1.py: scipt1.py:
from folder2 import module1
module1.say_hello()
Generally, python modules need to be installed for python to find them.一般需要安装 python 模块才能找到 python 模块。 One side rule is that python will look in a script's path to see if the module is there.
一个附带规则是 python 将查看脚本的路径以查看模块是否存在。 Move
script1.py
down a level, make sure you have an __init__.py
and it will work.将
script1.py
下移一级,确保你有一个__init__.py
并且它会工作。
└── root
├── script1.py
│
└── folder2
├── __init__.py
├── module1.py
You could also have script1.py
insert its grandparent directory into sys.path
.您还可以让
script1.py
将其祖父目录插入sys.path
。 But really the best way to solve the problem is to make the package installable by adding a setup.py.但真正解决问题的最佳方法是通过添加 setup.py 使 package 可安装。 An extremely primitive version is
一个极其原始的版本是
import setuptools
setuptools.setup(
name="Foobar",
packages=setuptools.find_packages(),
scripts=["folder1/script1.py"]
)
and your directory can be你的目录可以是
└── root
├── setup.py
├── folder1
│ ├── script1.py
│
└── folder2
├── __init__.py
├── module1.py
Now you can do python setup.py develop
to run your script from your development directory.现在您可以执行
python setup.py develop
从开发目录运行脚本。 Or python setup.py install
(frequently in a venv you created) to make it a standard install.或
python setup.py install
(通常在您创建的 venv 中)使其成为标准安装。
Right usage for init with double underscores;双下划线 init 的正确用法;
__init__
I added _ init _.py to the folders but still couldn't find a solution.
我将 _ init _.py 添加到文件夹中,但仍然找不到解决方案。
You write init with just one.你只用一个写 init 。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.