2

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?

Ken Kinder
  • 12,654
  • 6
  • 50
  • 70
Nico Schlömer
  • 53,797
  • 27
  • 201
  • 249
  • 1
    in the code ? otherwise u can check with `pip list` – Constantin Guidon Jun 15 '18 at 09:19
  • It needs to be in code. If necessary, parsing the output of `subprocess` could be it. – Nico Schlömer Jun 15 '18 at 09:20
  • @JodhSingh This is about whether a package is installed _with pip_. Perhaps you have a suggestion on how to improve the wording? – Nico Schlömer Jun 15 '18 at 09:33
  • 1
    I don't think this is a duplicate of the linked question. The linked one is about finding out if a package is installed. This one is specifically about finding out if it is installed *with pip*. – luator Feb 13 '20 at 08:25
  • Agreed, not a duplicate. I believe it can be solved with something like that: `import pkg_resources; pkg_resources.get_distribution('requests').get_metadata('INSTALLER')`. – sinoroc Feb 13 '20 at 09:47

2 Answers2

2

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.

sinoroc
  • 18,409
  • 2
  • 39
  • 70
  • Well, this works if it is indeed installed via pip. It fails with `FileNotFound` for Debian-installed packages because, e.g., `/usr/lib/python3/dist-packages/requests-2.22.0.egg-info/INSTALLER` is not installed there. That's good enough for me. – Nico Schlömer Feb 14 '20 at 13:38
  • Yes, this should be rewritten with the proper checks and/or try clauses in place. – sinoroc Feb 14 '20 at 13:43
0

You said subprocess.call() is allowed, so

available = not(subprocess.call(["pip", "show", "requests"]))
Nils Werner
  • 34,832
  • 7
  • 76
  • 98