Python:以编程方式运行“点列表" [英] Python: programmatically running "pip list"

查看:78
本文介绍了Python:以编程方式运行“点列表"的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在编写一些代码,以报告和协调两个由pip管理的python安装之间的差异.

I'm writing a bit of code that will report and reconcile differences between two pip-managed python installations.

如何在不进行子程序调用pip的情况下以编程方式获取pip list提供的信息?

How can I programmatically get the information provided by pip list without making a subprogram invocation of pip?

推荐答案

截至2019年2月1日,最重要的答案已过时,不再适用于较新版本的pip.

The top answers as of 2/1/2019 are outdated and no longer work with newer versions of pip.

但是不用担心-仍然可以通过编程方式获取软件包列表:

But no worries - it's still possible to get a list of packages programmatically:

A. _internal.main

from pip import _internal
_internal.main(['list'])

这将在Package中打印出三列.版本和位置

This will print out three columns with Package. Version, and Location

请注意,不建议使用pip的内部api.

Note that usage of pip's internal api is not recommended.

A. pkg_resources

import pkg_resources
print([p.project_name for p in pkg_resources.working_set])
# note that this is same as calling pip._vendor.pkg_resources.working_set

B. iter_modules

需要花费很长时间执行(在具有I5 CPU,SSD和8 gigs ram的计算机上约为300ms). 好处是它将有一个 far 更加广泛的模块列表,并且将输出可导入的名称.

Takes a long time to execute (~300ms on computer w/ I5 CPU, SSD, & 8 gigs ram). The benefit is that it will have a far more extensive list of modules and it will output importable names.

例如: python-dateutil 作为dateutil导入,但是iter_modules将为您提供可导入的名称:dateutil

Ex: python-dateutil is imported as dateutil, but iter_modules will give you the importable name: dateutil

from pkgutil import iter_modules
print([p.name for p in iter_modules()])

C.通过子进程在命令行中调用pip

解决这个问题的方法很简单,我将其留给读者练习

The solution to this is trivial and I'll leave this as an exercise to the reader

aka我太懒了,祝你好运! :D

aka I'm too lazy to do this, good luck! :D

这篇关于Python:以编程方式运行“点列表"的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆