In python you can do something like this to import a module using a string filename, and assign its namespace a variable on the local namespace.
x = __import__(str)
I'm wondering if there is a related function that will take take a string of Python code, instead of a path to a file with Python code, and return its namespace as a variable.
For example,
str = "a = 5";
x = importstr(str)
print x.a
#output is 5
I realize that I could write the string to a file, then use __import__
on it, but I'd like to skip the intermediate file if possible.
The reason for this is that I'm experimenting with metaprogramming in python, and it seems like a good solution to what I'm doing.
See Question&Answers more detail:
os 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…