Python ModuleNotFoundError使用来自导入另一自定义模块的自定义模块的函数时出错
我有一个与此类似的文件夹结构(我的示例包含所有必要的位): 其中Python ModuleNotFoundError使用来自导入另一自定义模块的自定义模块的函数时出错,python,python-3.x,module,runtime-error,python-import,Python,Python 3.x,Module,Runtime Error,Python Import,我有一个与此类似的文件夹结构(我的示例包含所有必要的位): 其中config.py只存储一些全局变量。它看起来有点像: global var1 var1 = "This is a test!" 在website\u one\u scraper.py中,它看起来像这样: import config def test_function(): # Do some web stuff... return = len(config.var1) if __name_
config.py
只存储一些全局变量。它看起来有点像:
global var1
var1 = "This is a test!"
在website\u one\u scraper.py
中,它看起来像这样:
import config
def test_function():
# Do some web stuff...
return = len(config.var1)
if __name__ == "__main__":
print(test_function)
from module import website_one_scraper
print(website_one_scraper.test_function())
而且scraper.py
看起来像这样:
import config
def test_function():
# Do some web stuff...
return = len(config.var1)
if __name__ == "__main__":
print(test_function)
from module import website_one_scraper
print(website_one_scraper.test_function())
website\u scraper\u one.py
在自己运行时工作正常,因此如果运行了的话,下的代码就可以了。但是,当我运行scraper.py
时,会出现以下错误:
ModuleNotFoundError: No module named 'config'
这是完整的错误和回溯(尽管名称不同,因为我已经为上面的示例更改了一些名称):
回溯(最近一次呼叫最后一次):
文件“c:\Users\User\Documents\Programming\Work\intrack web scraper\satellite\u scraper.py”,第3行,在
从模块导入平面4589
文件“c:\Users\User\Documents\Programming\Work\intrack web scraper\modules\planet4589.py”,第5行,在
导入配置
ModuleNotFoundError:没有名为'config'的模块
还请注意,在scraper.py
中,我尝试将模块导入网站\u one_scraper
中的替换为导入网站\u one_scraper
,从.modules导入网站\u one_scraper
,以及从。导入网站\u one\u scraper
,但它们都不起作用
我犯错误的原因可能是什么?这可能与我如何导入所有东西有关吗
(我正在使用Python 3.9.1)在您的网站中\u scraper\u one.py
,而不是导入config.py
尝试使用from。导入配置
说明:
- 。是当前包还是当前文件夹
- config是要导入的模块
这会直接创建错误ImportError:在运行website\u scraper\u one.py
时尝试在没有已知父包的情况下进行相对导入…是。它应该会告诉你错误。在模块
中,您创建了一个python包,其中包含相对导入
。因此,在本例中,您必须通过python-m modules.website\u scraper\u one
将website\u scraper\u one.py作为python模块运行,这将解决问题。谢谢