我试图将我正在处理的一个简单的web抓取应用程序的后端放入一个包中,但是这个应用程序依赖于从一个pickle python对象加载,我无法使用importlib将其加载到文件中。以前,当我将所有代码放在一个文件中,并且依赖open()时,所有代码都可以正常工作,但现在我在导入包时出错。发生此错误后,我尝试用importlib加载该文件,但无法使其正常工作
我是按照一个类似问题的答案中的步骤来回答的:How to read a (static) file from inside a Python package?
我的软件包中的文件结构是:
mypackage\
__init__.py
parse.py
search.py
categories\
categories.pickle
generate_categories_if_corrupted.py
init.py的内容:
from %mymodule% import search
发生错误的代码:
import importlib.resources as resources
from pickle import load
from . import categories
try:
with resources.open_binary(categories, "categories.pickle") as cat:
CATS = load(cat)
except FileNotFoundError:
raise FileNotFoundError("")
错误:
Traceback (most recent call last):
File "%mypackage%\parse.py", line 15, in <module>
with resources.open_binary(categories, "categories.pickle") as cat:
File "C:\Users\%me%\AppData\Local\Programs\Python\Python38\lib\importlib\resources.py", line 92, in open_binary
_check_location(package)
File "C:\Users\%me%\AppData\Local\Programs\Python\Python38\lib\importlib\resources.py", line 82, in _check_location
raise FileNotFoundError(f'Package has no location {package!r}')
FileNotFoundError: Package has no location <module '%mypackage%.categories' (namespace)>
During handling of the above exception, another exception occurred:
## just a FileNotFoundError with an error message, as expected.
我该如何解决这个问题?这是我第一次尝试用Python将代码打包
提前感谢您的回答
根据this answer on a related question(您可能想去投票表决这个答案),为了
importlib.resources
完成它的工作,包中必须有一个__init__.py
文件因此,在您的情况下,我认为应该有一个
mypackage/categories/__init__.py
文件(一如既往,该文件可以保留为空,但必须存在)相关问题 更多 >
编程相关推荐