简体   繁体   English

导入错误:无法从“importlib”导入名称“元数据”

[英]ImportError: cannot import name 'metadata' from 'importlib'

Under a python ( Python 3.7.5 (default, Oct 31 2019, 15:18:51) [MSC v.1916 64 bit (AMD64)] :: Anaconda, Inc. on win32 ) session launched in an Anaconda prompt, I get the error在蟒蛇( Python 3.7.5 (default, Oct 31 2019, 15:18:51) [MSC v.1916 64 bit (AMD64)] :: Anaconda, Inc. on win32 )会话下,在 Anaconda 提示符下启动,我得到错误

>>> import nbconvert
Traceback (most recent call last):
  File "C:\Users\user1\Anaconda\lib\site-packages\jsonschema\__init__.py", line 31, in <module>
    from importlib import metadata
ImportError: cannot import name 'metadata' from 'importlib' (C:\Users\user1\Anaconda\lib\importlib\__init__.py)

Effectively, metadata is not in importlib实际上, metadata不在importlib

>>> import importlib
>>> dir(importlib)
['_RELOADING', '__all__', '__builtins__', '__cached__', '__doc__', '__file__', '__import__', '__loader__', '__name__', '__package__', '__path__', '__spec__', '_bootstrap', '_bootstrap_external', '_imp', '_r_long', '_w_long', 'abc', 'find_loader', 'import_module', 'invalidate_caches', 'machinery', 'reload', 'sys', 'types', 'util', 'warnings']

This is the only reference I found, mentioning it was observed in some cases (weird?) in python 3.8.是我找到的唯一参考,提到在 python 3.8中的某些情况下(奇怪?)观察到它。


EDIT 1 : I am now able to remove the error.编辑 1 :我现在可以消除错误。 There is one change that does that: removing a string in the PYTHONPATH environment variable that led to an OSError: [WinError 123] ... after >>> import nbconvert .有一个更改可以做到这一点:删除PYTHONPATH环境变量中导致OSError: [WinError 123] ... after >>> import nbconvert Removing / adding that string, removes / reinstates the error.删除/添加该字符串,删除/恢复错误。

I am not certain if the fact that I did conda install nbconvert in an activated virtualenv (where I have python 3.8.0) also played a role;我不确定我在激活的 virtualenv(我有 python 3.8.0)中做了conda install nbconvert的事实是否也起作用了; I did not test before this install.在此安装之前我没有测试。

More importantly, I cannot figure out the connection between the OSError and the presence of a line from importlib import metadata .更重要的是,我无法弄清楚OSErrorfrom importlib import metadata一行存在之间的联系。


EDIT 2 : I have a virtualenv with python 3.8.0, where importlib does not have metadata either.编辑 2 :我有一个带有 python 3.8.0 的 virtualenv,其中importlib也没有metadata So I still cannot figure out why the presence of a line from importlib import metadata .所以我仍然无法弄清楚为什么会出现一行from importlib import metadata

C:\> conda activate opencv
C:\> conda list
...
importlib_metadata        1.1.0                    py38_0    defaults
...
nbconvert                 5.6.1                    py38_0    defaults
...
C:\> python
Python 3.8.0 (default, Nov  6 2019, 16:00:02) [MSC v.1916 64 bit (AMD64)] :: Anaconda, Inc. on win32
Type "help", "copyright", "credits" or "license" for more information.
>>> import importlib
>>> dir(importlib)
['_RELOADING', '__all__', '__builtins__', '__cached__', '__doc__', '__file__', '__import__', '__loader__', '__name__', '__package__', '__path__', '__spec__', '_bootstrap', '_bootstrap_external', '_imp', '_pack_uint32', '_unpack_uint32', 'find_loader', 'import_module', 'invalidate_caches', 'reload', 'sys', 'types', 'warnings']
>>> import nbconvert
>>>

The issue was caused by a recent change in the library jsonschema.该问题是由库 jsonschema 中的最近更改引起的。 Looking at https://github.com/Julian/jsonschema/blob/master/jsonschema/init.py you'll see that there was a change on September 26, 2019 changing pkg_resources to importlib_metadata as a fallback for Python <3.8.查看https://github.com/Julian/jsonschema/blob/master/jsonschema/init.py,您会看到 2019 年 9 月 26 日发生了变化,将 pkg_resources 更改为 importlib_metadata 作为 Python <3.8 的后备。 However, this doesn't seem to work out of the box.但是,这似乎不是开箱即用的。

To fix the issue, you have to downgrade your jsonschema package to a version that predates the change:要解决此问题,您必须将 jsonschema 包降级到更改之前的版本:

pipenv install jsonschema==3.0.2

More information can be found here: https://blog.gaborschulz.com/my-jupyter-notebook-stopped-working.html更多信息可以在这里找到: https : //blog.gaborschulz.com/my-jupyter-notebook-stopped-working.html

To fix the issue, you have to downgrade your jsonschema package to a version that predates the change:要解决此问题,您必须将 jsonschema 包降级到更改之前的版本:

pip install jsonschema==3.0.2 pip 安装 jsonschema==3.0.2

Today, I ran into an error similar (but not exactly the same) to yours.今天,我遇到了与您类似(但不完全相同)的错误。

Starting from Python 3.8, the importlib module has a metadata submodule.从 Python 3.8 开始, importlib模块有一个metadata子模块。 For libraries running under older Python versions, the library importlib_metadata has been made to replicate the behaviour.对于在较旧 Python 版本下运行的库,库importlib_metadata已被用于复制行为。 For example, the jsonschema library (used by Jupyter notebooks), uses it as follows:例如, jsonschema库(由 Jupyter notebooks 使用),使用如下:

# __init__.py from jsonschema 3.2.0
try:
    from importlib import metadata
except ImportError: # for Python<3.8
    import importlib_metadata as metadata
__version__ = metadata.version("jsonschema")

To answer your first question, the cause of the error is most likely due to a mismatch in the versions of the installed libraries you were using.要回答您的第一个问题,错误的原因很可能是由于您使用的已安装库的版本不匹配。 This could a result of manual pip installs or perhaps other libraries failing to list proper dependency versions.这可能是手动 pip 安装或其他库未能列出正确依赖版本的结果。

Your second question (edit 1): importing nbconvert triggers the import of jsonschema , which will lead to the same error.你的第二个问题(编辑1):进口nbconvert触发器的进口jsonschema ,这将导致同样的错误。

You also mention an OSError, but don't give any details when/how it occurred.您还提到了 OSError,但没有提供任何详细信息何时/如何发生。 In my original problem (how I found your question), I found that the importlib_metadata library could throw an OSError when some user folders are not accessible due to permissions.在我最初的问题中(我如何找到您的问题),我发现当某些用户文件夹由于权限而无法访问时, importlib_metadata库可能会引发 OSError。 They fixed this in version 1.4.他们在 1.4 版中修复了这个问题。

Your last question (edit 2): you are using dir() , which lists the attributes of importlib , however, importlib.metadata is a valid module that is simply not listed as an attribute.您的最后一个问题(编辑 2):您正在使用dir() ,它列出了importlib的属性,但是, importlib.metadata是一个有效的模块,只是没有作为属性列出。 It can be imported in python 3.8:它可以在python 3.8中导入:

Python 3.8.1 (default, Jan  8 2020, 15:55:49) [MSC v.1916 64 bit (AMD64)] :: Anaconda, Inc. on win32
Type "help", "copyright", "credits" or "license" for more information.
>>> dir('importlib')
['__add__', '__class__', '__contains__', '__delattr__', '__dir__', '__doc__', '__eq__', '__format__', '__ge__', '__getattribute__', '__getitem__', '__getnewargs__', '__gt__', '__hash__', '__init__', '__init_subclass__', '__iter__', '__le__', '__len__', '__lt__', '__mod__', '__mul__', '__ne__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__rmod__', '__rmul__', '__setattr__', '__sizeof__', '__str__', '__subclasshook__', 'capitalize', 'casefold', 'center', 'count', 'encode', 'endswith', 'expandtabs', 'find', 'format', 'format_map', 'index', 'isalnum', 'isalpha', 'isascii', 'isdecimal', 'isdigit', 'isidentifier', 'islower', 'isnumeric', 'isprintable', 'isspace', 'istitle', 'isupper', 'join', 'ljust', 'lower', 'lstrip', 'maketrans', 'partition', 'replace', 'rfind', 'rindex', 'rjust', 'rpartition', 'rsplit', 'rstrip', 'split', 'splitlines', 'startswith', 'strip', 'swapcase', 'title', 'translate', 'upper', 'zfill']
>>> from importlib import metadata
>>> dir(metadata)
['ConfigParser', 'Distribution', 'DistributionFinder', 'EntryPoint', 'FileHash', 'MetaPathFinder', 'MetadataPathFinder', 'PackageNotFoundError', 'PackagePath', 'PathDistribution', '__all__', '__builtins__', '__cached__', '__doc__', '__file__', '__loader__', '__name__', '__package__', '__spec__', 'abc', 'collections', 'csv', 'distribution', 'distributions', 'email', 'entry_points', 'files', 'functools', 'import_module', 'io', 'itertools', 'metadata', 'operator', 'os', 'pathlib', 're', 'requires', 'starmap', 'suppress', 'sys', 'version', 'zipfile']
>>>

I had the same issue of json schema while launching the jyputer notebook.启动 jyputer 笔记本时,我遇到了同样的 json 模式问题。 Indeed this issue is owing to the lastest update in jsonschema.事实上,这个问题是由于 jsonschema 中的最新更新造成的。 By downgrading the jsonshema to 3.0.2 the error ImportError: cannot import name 'metadata' from 'importlib ' resolved and finally the jyputer notebook and jyputer lab launched.通过将 jsonshema 降级到 3.0.2,错误ImportError: cannot import name 'metadata' from 'importlib ' 解决了,最后 jyputer notebook 和 jyputer lab 启动。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM