importlib: import X as Y; from A import B

dn PythonList at DancesWithMice.info
Sun Aug 9 00:10:37 EDT 2020


On 09/08/2020 15:23, Jason Friedman wrote:
> 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.

Try: The import system (https://docs.python.org/3/reference/import.html) 
and Simple Statements 
(https://docs.python.org/3/reference/simple_stmts.html?highlight=import#grammar-token-import-stmt)

Remember that you can test to ensure a library is available, or take 
evasive-action if it is not:
 >>> import so
Traceback (most recent call last):
   File "<stdin>", line 1, in <module>
ModuleNotFoundError: No module named 'so'

(there is a module called "os" though!)
-- 
Regards =dn


More information about the Python-list mailing list