Reputation: 58921
Checking if a particular package is available from within Python can be done via
try:
import requests
except ImportError:
available = False
else:
available = True
Additionally, I would like to know if the respective package has been installed with pip
(and can hence been updated with pip install -U package_name
).
Any hints?
Upvotes: 2
Views: 10349
Reputation: 22453
I believe one way to figure out if a project has been installed by pip is by looking at the content of the INSTALLER
text file in the distribution's dist-info
directory for this project. With pkg_resources
from setuptools this can be done programmatically like the following (error checking omitted):
import pkg_resources
pkg_resources.get_distribution('requests').get_metadata('INSTALLER')
This would return pip\n
, in case requests
was indeed installed by pip.
Upvotes: 2
Reputation: 36849
You said subprocess.call()
is allowed, so
available = not(subprocess.call(["pip", "show", "requests"]))
Upvotes: 0