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?

5
  • 1
    in the code ? otherwise u can check with pip list Commented Jun 15, 2018 at 9:19
  • It needs to be in code. If necessary, parsing the output of subprocess could be it. Commented Jun 15, 2018 at 9:20
  • @JodhSingh This is about whether a package is installed with pip. Perhaps you have a suggestion on how to improve the wording? Commented Jun 15, 2018 at 9: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. Commented Feb 13, 2020 at 8: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'). Commented Feb 13, 2020 at 9:47

2 Answers 2

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.

Sign up to request clarification or add additional context in comments.

2 Comments

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.
Yes, this should be rewritten with the proper checks and/or try clauses in place.
0

You said subprocess.call() is allowed, so

available = not(subprocess.call(["pip", "show", "requests"]))

2 Comments

Gives False for me although requests is installed with pip.
I forgot a not()... retval = 0 means success, but casts to False. retval != 0 means failed but casts to True :-)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.