如何以编程方式查找已安装包的详细信息(pip show等效)?



我知道有一个命令pip show用于目的,但我想知道是否有可能我可以通过做import pip获取细节?当你运行pip show时,它会给出如下信息:

pip show requests
Name: requests
Version: 2.26.0
Summary: Python HTTP for Humans.
Home-page: https://requests.readthedocs.io
Author: Kenneth Reitz
Author-email: me@kennethreitz.org
License: Apache 2.0
Location: /anaconda3/lib/python3.7/site-packages
Requires: urllib3, certifi, charset-normalizer, idna
Required-by: yarg, wordpress-api, WooCommerce, web3, vvm, tweepy, tika, stellar-sdk, stellar-base-sseclient, Sphinx, spacy, smart-open, requests-toolbelt, requests-oauthlib, requests-html, python3-nmap, python-binance, pyArango, poetry, pigar, pandas-datareader, MechanicalSoup, mara-pipelines, kubernetes, ipfshttpclient, hdfs, google-cloud-storage, google-api-core, discum, conda, conda-build, ccxt, CacheControl, browsermob-proxy, bravado, apache-beam, anaconda-project, anaconda-client, alpha-vantage, facebook-sdk

我需要Required-by字段的数据。

使用pip源代码,我找到了以下解决方案在Python 3.8.1和pip 21.0.1下运行。

from pip._internal.commands.show import search_packages_info as search_packages_info

package_name='requests'
# here I use next, because search_packages_info returns a generator
package_info=next(search_packages_info([package_name]))
required_by=package_info['required_by']

示例输出(取决于所使用的python环境)

['requests-unixsocket', 'pysolr', 'jupyterlab-server']
import pip
def show(package):
if hasattr(pip, 'main'):
pip.main(['show', package])
else:
pip._internal.main(['show', package])
show('requests')

或者使用当前运行时更好:

import subprocess
import sys
def show(package):
subprocess.check_call([sys.executable, "-m", "pip", "show", package])


show('requests')

答案受到这个答案的启发(过度劳累)

相关内容

最新更新