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

1 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
Run Code Online (Sandbox Code Playgroud)

我称之为:

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
Run Code Online (Sandbox Code Playgroud)

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

Bła*_*lik 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'))
Run Code Online (Sandbox Code Playgroud)

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

您可能还会发现JSON很有用:请参阅json 模块

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