是否可以从字符串运行python变量声明?

时间:2018-07-25 00:14:34

标签: python string python-2.x

这是我要寻找的行为...

"a = 2" # execute this line
print a
> 2

我知道exec语句,但是我需要它在python 2和3中工作,而python 3不允许exec创建局部变量。还有其他解决方法吗?

编辑:就像我说的-我知道我不能使用exec,公认的重复答案是说使用exec

1 个答案:

答案 0 :(得分:3)

我不必认为这是个好主意...

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://repl.it/repls/BiodegradableLiveProgrammer

相关问题