[英]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()
並不完全是為您要實現的目標而設計的。 在這里使用它會給你帶來不必要的麻煩。
編輯:將__import__()
替換為 import_module import_module()
。 不鼓勵使用前者。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.