How to retrieve pip requirements (freeze) within Python?

余生颓废 提交于 2019-12-21 09:18:16

问题


I posted this question on the git issue tracker: https://github.com/pypa/pip/issues/2969

Can we have some manner of calling pip freeze/list within python, i.e. not a shell context?

I want to be able to import pip and do something like requirements = pip.freeze(). Calling pip.main(['freeze']) writes to stdout, doesn't return str values.


回答1:


There's a pip.operation.freeze in newer releases (>1.x):

try:
    from pip._internal.operations import freeze
except ImportError:  # pip < 10.0
    from pip.operations import freeze

x = freeze.freeze()
for p in x:
    print p

Output is as expected:

amqp==1.4.6
anyjson==0.3.3
billiard==3.3.0.20
defusedxml==0.4.1
Django==1.8.1
django-picklefield==0.3.1
docutils==0.12
... etc




回答2:


Actually from pip >= 10.0.0 package operations.freeze has moved to pip._internal.operations.freeze.

So the safe way to import freeze is:

try:
    from pip._internal.operations import freeze
except ImportError:
    from pip.operations import freeze



回答3:


The other answers here are unsupported by pip: https://pip.pypa.io/en/stable/user_guide/#using-pip-from-your-program

According to pip developers:

If you're directly importing pip's internals and using them, that isn't a supported usecase.

try

reqs = subprocess.check_output([sys.executable, '-m', 'pip', 'freeze'])


来源:https://stackoverflow.com/questions/31304041/how-to-retrieve-pip-requirements-freeze-within-python

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!