18 Aug 2020

Installing and Using a `pip` Package From Within a Python Script

Recently, I needed the capability to install a package from PyPI via the pip package manager from within a Python script and use it from within the very same script. As it was a bit trial and error and I had to go through several different sites and posts to finally find a working solution, I thought I’d share it here (aka so that I’ll be able to copy and paste this the next time I need it myself 👿):

def install_pip_package(pkg, install_name=None):
    import importlib
    import sys
    from subprocess import check_call
    import site

    except ImportError:
        if install_name is None:
            install_name = pkg
            "-m", "pip", "install", install_name

Okay, so that’s the whole magic. By default, you can call this function like this:

# Ensure `termcolor` is installed:

# Now we can safely import it:
import termcolor

In case the name for importing the module and installing it via pip differ, you can call it like this:

# Ensure the `dialog` module is available, if not, install it,
# but keep in mind it is called `pythondialog` in PyPI:
install_pip_package("dialog", install_name="pythondialog")

# Now we can safely use it:
import dialog

As I like to explain things, here some words on the function itself:

  • We try to import the desired module to see if it already is there.
  • If this yields an ImportError, we know it is not present. In this case, we de facto use python -m pip install <install_name> to install it.
  • If this succeeds, we explicitly reload the site module, which ensures that the next attempt to import the just installed module will in fact find it.

Well, that’s it. Maybe a site note that such an approach will not replace proper deployment and packaging dependencies as an app. But in environments like the one I needed this for, it is super handy 😉

Thank You For Reading
Martin Hoeher

I am a software/firmware developer, working in Dresden, Germany. In my free time, I spent some time on developing apps, presenting some interesting findings here in my blog.

Your comment has been filed

We'll review it and it will appear here as soon as we're done.

Sorry, something went wrong...

Your comment could not be posted.

Regarding your personal information...
  • The name you enter will be shown next to your comment. You may enter your real name or whatever you like.
  • Your e-mail will be used to show an image representing you next to your comment. We do not store nor show your address somewhere. Instead, an ID will be calculated from it and stored. This ID is then used to retrieve an image from Gravatar.