簡體   English   中英

如何在 Python 中檢索 pip 要求(凍結)?

[英]How to retrieve pip requirements (freeze) within Python?

我在 git 問題跟蹤器上發布了這個問題: https : //github.com/pypa/pip/issues/2969

我們可以通過某種方式在 python 中調用 pip freeze/list,即不是 shell 上下文嗎?

我希望能夠導入 pip 並執行類似 requirements = pip.freeze() 的操作。 調用 pip.main(['freeze']) 寫入標准輸出,不返回 str 值。

在較新的版本 (>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

輸出如預期:

amqp==1.4.6
anyjson==0.3.3
台球==3.3.0.20
defusedxml==0.4.1
姜戈==1.8.1
django-picklefield==0.3.1
文檔工具==0.12
... 等等

pip 不支持這里的其他答案: https : //pip.pypa.io/en/stable/user_guide/#using-pip-from-your-program

根據 pip 開發人員的說法:

如果您直接導入 pip 的內部結構並使用它們,則這不是受支持的用例。

嘗試

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

實際上從pip >= 10.0.0operations.freeze已移至pip._internal.operations.freeze

所以導入freeze的安全方法是:

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

不建議依賴“私有”函數,例如pip._internal.operatons 您可以改為執行以下操作:

import pkg_resources
env = dict(tuple(str(ws).split()) for ws in pkg_resources.working_set)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM