importlib: import X as Y; from A import B

Jason Friedman jsf80238 at gmail.com
Sat Aug 8 23:23:28 EDT 2020


I have some code I'm going to share with my team, many of whom are not yet
familiar with Python. They may not have 3rd-party libraries such as pandas
or selenium installed. Yes I can instruct them how to install, but the path
of least resistance is to have my code to check for missing dependencies
and attempt to install for them. This code works as desired:

import importlib
import subprocess

PIP_EXE = "/opt/python/bin/pip3"

for module_name in ("module1", "module2", "module3"):
    try:
        importlib.import_module(module_name)
    except ModuleNotFoundError:
        install_command = f"{PIP_EXE} install {module_name}"
        status, output = subprocess.getstatusoutput(install_command)
        if not status:
            importlib.import_module(module_name)
            print(f"Successfully installed {module_name}.")
        else:
            print(f"Error when attempting to install {module_name}:
{output}")

The cherry-on-top would be to import with the "aliasing" and "from" they
will most likely see on the web, so that my code matches what they see
there. In other words, instead of:

import pandas
df = pandas.from_csv (...)
import selenium
browser = selenium.webdriver.Firefox()

on the web they will typically see:

import pandas as pd
df = pd.from_csv (...)
from selenium import webdriver
browser = webdriver.Firefox()

I don't see anything in the importlib module documentation that supports
this.


More information about the Python-list mailing list