我正在尝试从列表中导入模块。这将允许更容易编辑导入的模块,更清晰的错误消息和更好的错误处理。这基本上就是我想做的事情:
imports = ['sys', 'itertools', 'datetime', 'os']
for x in imports:
try:
import x
print "Successfully imported ", x, '.'
except ImportError:
print "Error importing ", x, '.'
这里的问题是它尝试导入x,而不是x应该保持的值。我意识到要从列表导入我可以做类似下面的事情,但我没有看到用它来处理错误的方法:
imports = ['sys', 'itertools', 'datetime', 'os']
modules = map(__import__, imports)
有没有办法将错误处理与此方法集成,还是应该尝试不同的方法?
答案 0 :(得分:5)
而不是将它们全部映射到___import__
,只需将每个模块一次附加到for循环内的列表modules
中:
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, '.'
但请注意,大多数Python程序员更喜欢使用importlib.import_module
而不是__import__
来执行此任务。
另请注意,使modules
字典而不是列表更好:
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, '.'
现在,而不是索引:
modules[0].version
modules[3].path
您可以按名称访问模块:
modules["sys"].version
modules["os"].path
答案 1 :(得分:1)
这在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)
导入子模块:
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"
导入所有内容:
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
导入实例或其他内容
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
从模块的子模块导入所有内容:
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
答案 2 :(得分:0)
您可以修改import x
行以使用__import__(x)
格式
imports = ['sys', 'itertools', 'datetime', 'os','doesntexit']
for x in imports:
try:
__import__(x)
print "Success"
except ImportError:
print "Error ", x
输出:
Success
Success
Success
Success
Error doesntexit
答案 3 :(得分:0)
您可以通过编程方式导入,并使用import x as y
与globals
具有相同的作用:
packages_to_import = [{'name': 'numpy'
'as': 'np'}]
for package in packages:
package_name = package['name']
import_as = package.get('as', package_name)
globals()[import_as] = __import__(package_name)
print(np.version.full_version)
答案 4 :(得分:0)
没有一个投票最多的选项对我有用。它们似乎已成功导入,但是以后无法使用。万一您遇到相同的问题,this tutorial会为我解决。
modules = ['sys', 'itertools', 'datetime', 'os']
for lib in modules:
globals()[lib] = __import__(lib)
PS:我猜他们之前没有被添加到我的全局变量中