帮助程序函数在另一个文件中,尝试导入时出现 ModuleNotFoundError

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

我有一个使用 scrapy 的简单 Python 项目。我的文件结构如下所示:

top_level_folder
|-scraper
|--spiders
|---help_functions.py
|---<some more files>
|--items.py
|--pipelines.py
|--settings.py
|--<some more files>

help_functions.py 定义了几个函数,例如

add_to_items_buffer

在 pipelines.py 中,我正在尝试做...

from help_functions import add_to_items_buffer

...

class BlahPipeline:
    def process_item(self, item, spider):
       ...
       add_to_items_buffer(item)
       ...

当我尝试运行它时,我得到了

ModuleNotFoundError: No module named 'help_functions'
。执行
from spiders.help_functions import add_to_items_buffer
会引发类似的错误。

这是怎么回事?我想我误解了 Python 导入工作原理的一些基本原理。

python scrapy
1个回答
0
投票

如果

add_to_items_buffer
文件中有
top_level_folder/scraper/spiders/help_functions.py
函数,并且
pipelines.py
中有
top_level_folder/scraper/pipelines.py
,则需要像这样导入它:

from spiders.help_functions import add_to_items_buffer
© www.soinside.com 2019 - 2024. All rights reserved.