这就是我要找的行为。
"a = 2" # execute this line
print a
> 2
我知道exec
语句,但我需要它在Python2和3中工作,而Python3不允许exec创建局部变量。有没有别的办法来解决这个问题呢?
编辑:就像我说的--我知道我不能使用exec
,假设重复的答案是使用exec
。
发布于 2018-07-25 08:31:29
我不一定认为这是个好主意……
import ast
def parse_assignment(s):
lhs,rhs = s.split("=",1)
globals()[lhs] = ast.literal_eval(rhs)
parse_assignment("hello=5")
print(hello)
parse_assignment("hello2='words'")
print(hello2)
parse_assignment("hello3=[1,'hello']")
print(hello3)
https://stackoverflow.com/questions/51509206
复制相似问题