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
map
you are passing the right function :__import__
. Just use__import__(x)
in yourtry
block – StettinPyFlakes
from warning you about missing or unused imports, make sorting and editing imports harder, and obfuscate / hide error messages. – Finder