As part of the testing regime for building a python application [a Jupyter notebook, in this instance], I want to test that all the modules installed in the system will actually load.
import module from string variable pointed me to build the following code:
import re
import subprocess
s_counter = 0
f_counter = 0
errors = []
libraries = []
output = subprocess.run(['conda', 'list'], stdout=subprocess.PIPE).stdout.decode('utf-8').splitlines()
for line in output:
if not re.match('\s*#', line):
words = re.split('\s+', line)
if words[0] != 'python':
libraries.append(words[0])
for lib in libraries:
try:
lib_obj = __import__(lib)
globals()[lib] = lib_obj
s_counter += 1
except ImportError:
errors.append("ERROR: missing python library: " + lib)
f_counter += 1
print(f"Successfuly loaded {s_counter} libraries, failed to load {f_counter}")
print(f"{errors}")
The problem with this simplistic solution is that it assumes the module name is the same as the import
name.... and often it isn't.
For example: .... install beautifulsoup4
and from bs4 import BeautifulSoup
So the question is, how do I find out the import
string for a module... programatically?