[英]Python : importing a list from other file with exec()
I am trying to import a list from a file in python, and i don't know the name of the list or the file.我正在尝试从 python 中的文件导入列表,但我不知道列表或文件的名称。
I am asking them in the code, and when I get them, i am trying to import the list,我在代码中询问他们,当我得到它们时,我正在尝试导入列表,
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
I call it:我称之为:
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
But i can't get the output, of exec, which is my list, i know i can get it as string but i would like to get it as list, is that possible?但我无法获得 exec 的 output,这是我的列表,我知道我可以将其作为字符串获取,但我想将其作为列表获取,这可能吗?
Try import_module()
with getattr()
instead:尝试使用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()
was not exactly made for what you're trying to achieve. exec()
并不完全是为您要实现的目标而设计的。 Using it here will give you unnecessary headaches.在这里使用它会给你带来不必要的麻烦。
You might also find JSON useful: see json module .您可能还会发现JSON很有用:请参阅json 模块。
Edit: replaced __import__()
with import_module()
.编辑:将__import__()
替换为 import_module import_module()
。 Usage of the former is discouraged.不鼓励使用前者。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.