Python:使用exec()从其他文件导入列表

时间:2020-10-26 20:47:42

标签: python python-3.x

我正在尝试从python文件中导入列表,但我不知道列表或文件的名称。

我在代码中询问他们,当我得到它们时,我正在尝试导入列表,

def listIMP(ITEM):
    listIMP = "from {0} import {1}".format(ITEM[0],', '.join(str(i) for i in ITEM[1:])) # generating command
    exec(listIMP) #exec generated command

我称之为:

listN = input('!\n')# asking for list name
name = input('>') # asking for file name
name = name[:-3] #deleting .py
list1 = [name, listN] 
listIMP(list1) # calling my func

但是我无法获取exec的输出,这是我的列表,我知道我可以将它作为字符串获取,但是我想将其作为列表获取,这有可能吗?

1 个答案:

答案 0 :(得分:5)

尝试用import_module()来尝试getattr()

from importlib import import_module

def import_from(module, variable):
    return getattr(import_module(module), variable)

print(import_from('module_name', 'variable_name'))

exec()并非完全针对您要实现的目标。在这里使用它会给您带来不必要的麻烦。

您可能还会发现JSON有用:请参见json module

编辑:将__import__()替换为import_module()。不鼓励使用前者。