How to find “import name” of any package in Python?

后端 未结 3 1298
孤街浪徒
孤街浪徒 2020-12-06 05:31

I wonder if is there any reliable and consistant way to get a Python package\'s \"import name\" / namespace. For example;

Package; django-haystack

3条回答
  •  没有蜡笔的小新
    2020-12-06 05:52

    Wheels

    I know this is an old question, but wheel packages have since been invented! Since a wheel is simply a zip file that gets extracted into the lib/site-packages directory, an examination of the contents of the wheel archive can give you the top level imports.

    >>> import zipfile
    >>> zf = zipfile.ZipFile('setuptools-35.0.2-py2.py3-none-any.whl')
    >>> top_level = set([x.split('/')[0] for x in zf.namelist()])
    >>> # filter out the .dist-info directory
    >>> top_level = [x for x in top_level if not x.endswith('.dist-info')]
    >>> top_level 
    ['setuptools', 'pkg_resources', 'easy_install.py']
    

    So setuptools actually gives you three top level imports!

    pip download

    pip now has a download command, so you can simply run pip download setuptools (or whatever package you like) and then examine it.

    Reverse look up

    Unfortunately I haven't found an easy way to go the other direction yet. That is, given the import name, what is the package name. This can be a problem if you are looking at some example code or maybe if you use Anaconda that comes with a bunch of packages pre-installed and you want to know the actual package name.

提交回复
热议问题