简体   繁体   English

从列表或字典中导入模块在Python?

[英]Import modules from a list or dict in Python?

Im fairly versed in Python, however this has been an issue for quite some time for me. 我相当精通Python,但是对于我来说这已经是一个问题了。

I have a folder full of scripts that the artists in my studio use within Nuke. 我有一个充满脚本的文件夹,我的工作室中的艺术家可以在Nuke中使用这些脚本。 In order for them to be accessible from within, I need to import them via and init.py file that Nuke reads on load. 为了从内部访问它们,我需要通过Nuke加载时读取的init.py文件导入它们。

I would like to be able to make a list of these values, either via a glob search to find everything applicable, or a declared list like: 我希望能够通过全局搜索找到适用的所有内容或声明的列表,例如:

my_list = ['mod_1', 'mod_2', 'mod_3']

Yet I have been unable to find a method that can handle this. 但是我一直找不到能够解决这个问题的方法。 I know I can use variable names to find the modules and import them via: 我知道我可以使用变量名来找到模块​​并通过以下方式导入它们:

module = getattr(__import__(package, fromlist=[name]), name)

or 要么

module = __import__(var)

but both of these methods require me to assign a name for the module I am importing. 但是这两种方法都要求我为我要导入的模块分配一个名称。

I am looking for a way to do something along these lines: 我正在寻找一种方法来遵循以下原则:

capture = glob.glob('/scriptLocation/*.py')
for i in capture:
    import i

or 要么

my_list = ['mod_1', 'mod_2', 'mod_3']
for i in capture:
    import i

TIA! TIA!

Try this: 尝试这个:

modules = map(__import__, moduleNames)

Verify this link for more : (Example 16.15) 验证此链接以获取更多信息 :(示例16.15)

>>> moduleNames = ['sys', 'os', 're', 'unittest'] 1
>>> moduleNames
['sys', 'os', 're', 'unittest']
>>> modules = map(__import__, moduleNames)        2
>>> modules                                       3
[<module 'sys' (built-in)>,
<module 'os' from 'c:\Python22\lib\os.pyc'>,
<module 're' from 'c:\Python22\lib\re.pyc'>,
<module 'unittest' from 'c:\Python22\lib\unittest.pyc'>]
>>> modules[0].version                            4
'2.2.2 (#37, Nov 26 2002, 10:24:37) [MSC 32 bit (Intel)]'
>>> import sys
>>> sys.version
'2.2.2 (#37, Nov 26 2002, 10:24:37) [MSC 32 bit (Intel)]'

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

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