繁体   English   中英

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

[英]Python : importing a list from other file with exec()

我正在尝试从 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 的 output,这是我的列表,我知道我可以将其作为字符串获取,但我想将其作为列表获取,这可能吗?

尝试使用getattr()代替import_module() ():

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 模块

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

暂无
暂无

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

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