Import modules from a list in Python
Instead of mapping them to ___import__
all at one, just append each module to the list modules
one at a time inside the for-loop:
imports = ['sys', 'itertools', 'datetime', 'os']
modules = []
for x in imports:
try:
modules.append(__import__(x))
print "Successfully imported ", x, '.'
except ImportError:
print "Error importing ", x, '.'
Note however that most Python programmers prefer the use of importlib.import_module
rather than __import__
for this task.
Note too that it might be better to make modules
a dictionary instead of a list:
imports = ['sys', 'itertools', 'datetime', 'os']
modules = {}
for x in imports:
try:
modules[x] = __import__(x)
print "Successfully imported ", x, '.'
except ImportError:
print "Error importing ", x, '.'
Now, instead of by index:
modules[0].version
modules[3].path
you can access the modules by name:
modules["sys"].version
modules["os"].path
This worked for me on Python 3.7
modules = ["sys","os","platform","random","time","functools"]
for library in modules:
try:
exec("import {module}".format(module=library))
except Exception as e:
print(e)
print(sys.argv)
Importing a submodule:
modules = ["PyQt5"] # pip install PyQt5
submodules = ["QtCore"]
for library in modules:
for sublibrary in submodules:
try:
exec("from {m} import {s}".format(m=library, s=sublibrary))
except Exception as e:
print(e)
print(dir()) # Includes QtCore
print(dir(QtCore)) # All functions, classes and variables are exactly correct as with "from PyQt5 import QtCore"
Importing everything:
modules = ["sys","os","platform","random","time","functools"]
for library in modules:
try:
exec("from {module} import *".format(module=library))
except Exception as e:
print(e)
print(dir()) # Exactly working as thought
Importing a instance or something:
modules = ["PyQt5"] # pip install PyQt5
submodules = ["QtCore"]
func = ["QCoreApplication"]
for library in modules:
for f in func:
for sublibrary in submodules:
try:
exec("from {m}.{s} import {f}".format(m=library, s=sublibrary, f=f))
except Exception as e:
print(e)
print(dir()) # Includes QCoreApplication instance
Importing everything from a modules's submodule:
modules = ["PyQt5"] # pip install PyQt5
submodules = ["QtCore"]
for library in modules:
for sublibrary in submodules:
try:
exec("from {m}.{s} import *".format(m=library, s=sublibrary)) # Didn't mention f"" strings all the times. But for beginners .format is better.
except Exception as e:
print(e)
print(dir()) # Includes all PyQt5.QtCore stuff