如何查找特定模块的包名称?

use*_*745 4 python pip

如果我们有 python 代码,但pip在运行代码之前没有关于要安装哪些包的说明,那么我们运行它:

import inception5h

ERROR: Could not find a version that satisfies the requirement inception5h (from versions: none)
ERROR: No matching distribution found for inception5h
Run Code Online (Sandbox Code Playgroud)

猜测是否安全 - 即尝试类似pip install inception5hor 的东西pip install inception

我假设在没有关于要安装哪个包的具体说明的情况下,我们只是猜测,因为(我认为),任何包理论上都可以具有任何名称的模块(也就是说,可能有许多带有名为 的模块的包inception5h)。

这种理解正确吗?有没有什么聪明的方法可以确定需要安装哪个软件包,最好不要猜测?

sin*_*roc 7

2021 年 5 月更新

如今,这应该相对简单importlib_metadata.packages_distributions()

See the documentation here: stdlib or external.


Original answer

That I know of, there is no straightforward (non-guess) way to deduce the name of a (PyPI) distribution package name when all you have is the name of an import package (or module). As explained in the this answer for example (linked by @hoefling in the comments to your question).

There is obviously the convention of having in each distribution package 1 top-level importable package (or module) with the same name.

So, for example pip install requests allows you to write the Python code import requests.

But it is just a convention and obviously there are outliers:

  • 有些有超过 1 个顶级 可导入包,例如setuptools
    • pip import setuptools
    • import setuptoolsimport pkg_resources
  • 有些具有完全不同的名称,例如项目PyYAML
    • pip install pyyaml
    • import yaml

在这种情况下,我想我可能会尝试在网络搜索引擎中查找导入包的名称,并希望找到一些导致发行包名称的结果。