[three]Bean

Installing from pip inside python or, a simple pip API

Jun 06, 2011 | categories: pip, python View Comments

So, it's a long story, but my bid to convert moksha's development tools to fabric was a terrible idea: mandatory sshd on dev boxes, passwords in the clear when chaining commands between systems, simple failure to work. It was the wrong tool for the job. Now I have my work cut out for me to replace it with something worthwhile.

I have a need to invoke pip from inside python and to do it within the current virtualenv. I googled and found this somewhat old thread on the virtualenv list which indicates that there's not much help out there.

Here's my stab at it.

import pip.commands.install

def install_distributions(distributions):
    command = pip.commands.install.InstallCommand()
    opts, args = command.parser.parse_args()
    # TBD, why do we have to run the next part here twice before actual install
    requirement_set = command.run(opts, distributions)
    requirement_set = command.run(opts, distributions)
    requirement_set.install(opts)

And a test to see if it works.

#!/usr/bin/env python

from blogmodule import install_distributions

def run_test():
    try:
        import markdown
        print "Markdown is installed!  Aborting."
        assert(False)
    except ImportError as e:
        print "Markdown isn't yet installed.  That's good."

    install_distributions(["Markdown"])

    try:
        import markdown
        print "Markdown is now installed.  That's good!"
    except ImportError as e:
        print "Markdown never got installed.  That's bad."
        assert(False)

if __name__ == '__main__':
    run_test()

Looking forward to doing something cool with this and python context managers to manage virtualenvs.

View Comments
blog comments powered by Disqus