【问题标题】:Cannot import 'collections.abc' when using windows subsystem for linux使用 linux 的 windows 子系统时无法导入“collections.abc”
【发布时间】:2019-05-27 20:18:37
【问题描述】:

我正在使用适用于 linux 的 windows 子系统(特别是适用于 Windows 的 Ubuntu)来运行一些 python 代码。当我尝试运行以下命令时:'import collections.abc',我收到以下错误:'ImportError: No module named abc'。

我可以导入'collections',但如果我尝试:'collections.abc',我会收到以下错误:'AttributeError:'module' object has no attribute 'abc''。

此外,我尝试在命令提示符下导入模块,而不使用 Ubuntu for Windows,并成功导入。

默认情况下,'collections' 模块应该包含在 python 中,所以我不确定它为什么会给我这个错误。

【问题讨论】:

  • 您使用的是什么版本的 Python? collections.abc 在 3.3 版本中引入。命令提示符中的python -V 是否返回与Ubuntu 子系统中的python -V 相同的版本号?
  • 你也可以import sys,然后print(sys.version_info)查看正在运行的Python版本。

标签: python windows-subsystem-for-linux


【解决方案1】:

来自Python 3 documentation for the collections module

在 3.3 版中更改:已移动 Collections Abstract Base Classescollections.abc 模块。为了向后兼容,它们继续可见 在这个模块中通过 Python 3.7。 随后,它们将被完全删除。

所以collections.abc 的任何内容已经存在于 Python collections 中找到 直接。

要支持所有版本的 Python,请使用 try/except 块:

try:  # works in Python >= 3.3
    import collections.abc as collections_abc
except ImportError:  # Python <= 3.2 including Python 2
    import collections as collections_abc

然后使用例如collections_abc.Sequence 而不是 collections.abc.Sequence 在 Python >= 3.3 和 collections.Sequence 在 Python 中

this other answer 中查看更长的讨论。

【讨论】:

    猜你喜欢
    • 2021-12-31
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-08-28
    • 2019-10-30
    • 1970-01-01
    • 2017-03-20
    • 2016-08-09
    相关资源
    最近更新 更多