简体   繁体   中英

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.

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?

Try import_module() with getattr() instead:

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. Using it here will give you unnecessary headaches.

You might also find JSON useful: see json module .

Edit: replaced __import__() with import_module() . Usage of the former is discouraged.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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