简体   繁体   English

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

[英]Python - Dynamically importing modules and assigning them local names

I'm fairly new to python, so I apologize for my lack of knowledge. 我对python还是很陌生,所以对我的知识不足深表歉意。

This is what I'm looking to do: 这就是我想要做的:

Say I currently have the following 说我目前有以下情况

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

I want to be able to do this through having a dictionary of packages and names, to achieve something like this 我希望能够通过拥有包和名称的字典来做到这一点,以实现这样的目标

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

How do I accomplish this? 我该如何完成?

The built-in function __import__ will do dynamic imports where the module name is specified in a variable. 内置函数__import__将执行动态导入,其中在变量中指定了模块名称。 And you can make the assignment by updating globals() directly: 您可以通过直接更新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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM