[英]How to retrieve pip requirements (freeze) within Python?
I posted this question on the git issue tracker: https://github.com/pypa/pip/issues/2969我在 git 问题跟踪器上发布了这个问题: https : //github.com/pypa/pip/issues/2969
Can we have some manner of calling pip freeze/list within python, ie not a shell context?我们可以通过某种方式在 python 中调用 pip freeze/list,即不是 shell 上下文吗?
I want to be able to import pip and do something like requirements = pip.freeze().我希望能够导入 pip 并执行类似 requirements = pip.freeze() 的操作。 Calling pip.main(['freeze']) writes to stdout, doesn't return str values.
调用 pip.main(['freeze']) 写入标准输出,不返回 str 值。
There's a pip.operation.freeze in newer releases (>1.x):在较新的版本 (>1.x) 中有一个 pip.operation.freeze:
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
amqp==1.4.6
anyjson==0.3.3anyjson==0.3.3
billiard==3.3.0.20台球==3.3.0.20
defusedxml==0.4.1defusedxml==0.4.1
Django==1.8.1姜戈==1.8.1
django-picklefield==0.3.1django-picklefield==0.3.1
docutils==0.12文档工具==0.12
... etc... 等等
The other answers here are unsupported by pip: https://pip.pypa.io/en/stable/user_guide/#using-pip-from-your-program pip 不支持这里的其他答案: https : //pip.pypa.io/en/stable/user_guide/#using-pip-from-your-program
According to pip developers:根据 pip 开发人员的说法:
If you're directly importing pip's internals and using them, that isn't a supported usecase.
如果您直接导入 pip 的内部结构并使用它们,则这不是受支持的用例。
try尝试
reqs = subprocess.check_output([sys.executable, '-m', 'pip', 'freeze'])
Actually from pip >= 10.0.0
package operations.freeze
has moved to pip._internal.operations.freeze
.实际上从
pip >= 10.0.0
包operations.freeze
已移至pip._internal.operations.freeze
。
So the safe way to import freeze
is:所以导入
freeze
的安全方法是:
try:
from pip._internal.operations import freeze
except ImportError:
from pip.operations import freeze
It's not recommended to rely on a "private" function such as pip._internal.operatons
.不建议依赖“私有”函数,例如
pip._internal.operatons
。 You can do the following instead:您可以改为执行以下操作:
import pkg_resources
env = dict(tuple(str(ws).split()) for ws in pkg_resources.working_set)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.