Python: programmatically running “pip list”

前端 未结 4 1933
梦如初夏
梦如初夏 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:20

    For completeness, here's vittore's pip.main() idea fleshed out with the capture of stdout. Of course using get_installed_distributions() is the preferred solution.

    import contextlib
    @contextlib.contextmanager
    def capture():
        import sys
        from cStringIO import StringIO
        oldout,olderr = sys.stdout, sys.stderr
        try:
            out=[StringIO(), StringIO()]
            sys.stdout,sys.stderr = out
            yield out
        finally:
            sys.stdout,sys.stderr = oldout, olderr
            out[0] = out[0].getvalue()
            out[1] = out[1].getvalue()
    
    with capture() as out:
        import pip
        pip.main(['list'])
    
    print out
        ['awscli (1.7.45)\nboto (2.38.0) ...
    

提交回复
热议问题