Python - 动态导入模块并为其分配本地名称

Python - Dynamically importing modules and assigning them local names

我是 python 的新手,所以对于我的知识不足深表歉意。

这就是我想要做的事情:

假设我目前有以下

import pandas as py
import numpy as np
...
import somePackage as someName

我希望能够通过包和名称的字典来实现这一点,以实现类似的目的

imports = {'pandas' : 'py', 'numpy' : 'np' ... 'somePackage' : 'someName'}
for package in imports.keys():
    import package as imports[package]

我该如何完成?

内置函数__import__ will do dynamic imports where the module name is specified in a variable. And you can make the assignment by updating globals()直接:

>>> imports = {'random':'r', 'statistics':'s'}
>>> for package, target in imports.items():
        globals()[target] = __import__(package)

>>> r.randrange(100)
16
>>> s.mean([10, 20, 61])
30.333333333333332