Python项目中的ModuleNotFoundError

问题描述 投票:0回答:1

我在Python中具有以下项目结构(...意味着我有n个crawler_.py文件)。

project
├── crawlers
│   ├── __init__.py
│   ├── crawler_1.py
│   ├── crawler_2.py
│   ...
│   ├── crawler_n.py
│   └── useful_functions.py
├── main.py
└── __init__.py

我需要将所有搜寻器从搜寻器导入到main中,所以我用这个。

# main.py
from crawlers import crawler_1
from crawlers import crawler_2
...
from crawlers import crawler_n

但是我在所有crawler_.py文件中也都需要useful_functions.py,因此我在每个文件中都使用了。

# crawler_.py
import useful_functions

但是当我运行main.py时,它尝试导入crawler_1时却得到了ModuleNotFoundError: No module named 'useful_functions'

所以我尝试了以下内容

# crawler_.py
from crawlers import useful_functions

并且当我运行main.py时它起作用。问题是我可能只想直接运行crawler_.py之一。使用最后一个import语句,我得到ModuleNotFoundError: No module named 'crawlers'。不知道如何解决这个问题,如果代码中有什么我应该调整的,或者我使用的结构从根本上是错误的(我完全可以调整项目结构)。

python structure python-import python-module directory-structure
1个回答
2
投票

您可以在crawler_n.py中使用它

if __name__ == '__main__':
    import useful_functions
else:
    import crawlers.useful_functions as useful_functions

[__name__ == '__main__'检查模块是被调用还是被导入,从而进行相应的导入。

© www.soinside.com 2019 - 2024. All rights reserved.