Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to retrieve the import name of a module from its pip requirements name?

After parsing requirements.txt, lets assume this is the list of pip modules:

>>> modules_req = ['beautifulsoup4','django-nose','ujson']
>>> for module in modules_req:
...     __import__(module)
... 
Traceback (most recent call last):
  File "<stdin>", line 2, in <module>
ImportError: No module named beautifulsoup4

How can we retreive the import name of these modules i.e. bs4 for beautifulsoup4, and django_nose for django-nose, for example ?

like image 417
DhruvPathak Avatar asked Oct 23 '25 14:10

DhruvPathak


1 Answers

i'm not sure this is what you actually want to do, but for installed packages you might get some mileage out of querying pkg_resources for package info:

$ pip freeze
beautifulsoup4==4.4.1

.

>>> import pkg_resources
>>> list(
        pkg_resources
        .get_distribution('beautifulsoup4')
        ._get_metadata('top_level.txt')
    )
['bs4']
like image 103
second Avatar answered Oct 25 '25 03:10

second



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!