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.
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 try: importlib.import_module(pkg) except ImportError: if install_name is None: install_name = pkg check_call([ sys.executable, "-m", "pip", "install", install_name ]) importlib.reload(site) finally: importlib.import_module(pkg)
Okay, so that’s the whole magic. By default, you can call this function like this:
# Ensure `termcolor` is installed: install_pip_package("termcolor") # 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
sitemodule, 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 😉