简体   繁体   中英

Checking if a package is installed specifically via pip

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?

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 .

Maybe you could retrieve all the packages installed by pip and check if yours is in the there.

import pip
return 'package' in pip.get_installed_distributions()

we can use pip list --format=json with subprocess

import subprocess
import ast

# here we will get a string, there will be a list of dictionary 
# with  name and version from all packages that we have, example: 
# [{"name": "amqp", "version": "2.2.2"}, {"name": "asn1crypto", "version": "0.24.0"}]
# also we need to `decode()`, because this is of type `bytes`   
packages = subprocess.check_output(
            ['pip', 'list', '--format=json'], stderr=subprocess.STDOUT).decode()

# name of our package that we search
name = 'requests'

# with ast.literal_eval() we transform the string to list
# and check if in this list of dictionary we have a pip package
print(any(name in package['name'] for package in ast.literal_eval(packages)))

Output

# if we search `requests`
True 

你说subprocess.call()是允许的,所以

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM