Python: programmatically running “pip list”

前端 未结 4 1909
梦如初夏
梦如初夏 2021-01-01 17:39

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

How can I programmatically get the information pr

4条回答
  •  清酒与你
    2021-01-01 18:24

    Update for Python 3.6 and Pip 19.0.1

    > from pip._internal.utils.misc import get_installed_distributions
    > p = get_installed_distributions()
    > pprint.pprint(p)
    
    [wheel 0.32.3 (/usr/local/lib/python3.7/site-packages),
     wcwidth 0.1.7 (/usr/local/lib/python3.7/site-packages),
     virtualenv 16.0.0 (/usr/local/lib/python3.7/site-packages),
     virtualenv-clone 0.3.0 (/usr/local/lib/python3.7/site-packages),
     urllib3 1.24.1 (/usr/local/lib/python3.7/site-packages),
     typing 3.6.6 (/usr/local/lib/python3.7/site-packages),
     terminaltables 3.1.0 (/usr/local/lib/python3.7/site-packages),
     ...
    
    

    Original Answer

    Pip is just python module, so just import it and call list:

    import pip
    
    pip.main(['list'])
    
    # you can get details on package using show:
    
    pip.main(['show', 'wheel'])
    

    Ok so there is better way:

    pip.utils.get_installed_distributions()
    

    returns you list of packages installed.

    packages = pip.utils.get_installed_distributions()
    
    p = packages[0]
    
    p.project_name 
    p.version
    p.egg_name
    p.location
    

    You can see what pip list is doing from the source code here

    Also get_installed_distributions accept whole bunch of parameters to return only local packages (from current virtualenv) etc. Please see help here.

    There is also underlying low level command from _vendor module:

    [p for p in pip._vendor.pkg_resources.working_set]
    

    However get_installed_distributions provide simplier api.

提交回复
热议问题