如何使用模块作为文本?

时间:2019-09-08 18:37:19

标签: python

我有一个包含模块的字典,现在我想使用模块的字符串值(请参见示例)。这可能吗?还是我最好只创建第二本词典?

import module1
import module2
import module3

module_dict = {
    'module1': module1
    'module2': module2
}

user_input = input()
module_dict[user_input].function()

#module3.function requires two strings to work, one of the string happens to be the name of the module
module3.function('foo', module_dict[user_input])

这是一个非常简化的版本,如果看起来令人困惑,请原谅我。我无法使用内置的str函数,因为它将导致module 'modulename' at 'path',这不是我想要的。

1 个答案:

答案 0 :(得分:1)

您可以从模块的__name__属性中获取模块的名称:

import itertools

print(itertools.__name__)

输出

itertools