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

可以从字符串运行python变量声明吗?,python,string,python-2.x,Python,String,Python 2.x,这就是我想要的行为 "a = 2" # execute this line print a > 2 我知道exec语句,但我需要它在Python2和Python3中工作,Python3不允许exec创建局部变量。还有别的办法吗 编辑:就像我说的-我知道我不能使用exec,公认的重复答案是使用exec,我不一定认为这是个好主意 import ast def parse_assignment(s): lhs,rhs = s.split("=",1) globals()[lhs

这就是我想要的行为

"a = 2" # execute this line
print a
> 2
我知道
exec
语句,但我需要它在Python2和Python3中工作,Python3不允许exec创建局部变量。还有别的办法吗


编辑:就像我说的-我知道我不能使用
exec
,公认的重复答案是使用
exec
,我不一定认为这是个好主意

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)

我不一定认为这是个好主意

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)

可能的重复我不建议
exec
eval
,但可以做
locals()['a']=2
(不说它好,但肯定更安全)@RafaelC:@RafaelC:它在函数内部失败,与
exec
失败的情况相同。@user2357112可以做
globals()['a']=2
,不确定推荐的可能的副本我不建议
exec
eval
,但可以做
locals()['a']=2
(不说它好,但肯定更安全)@RafaelC:@RafaelC:它在函数内部失败,与
exec
失败的情况相同。@user2357112可以做
globals()['a']=2
,不确定推荐我只是在写一个简单的脚本,不是企业级的python项目,所以这很好用。我很好奇,如果这种代码存在于许多人正在使用的大型python项目中,会产生什么后果?这只是一种奇怪的设置变量的方式,当事情基本上不顺利时,很难调试。。。没有太多的安全问题,大多数情况下,跟踪问题会变得很困难。我只是在编写一个简单的脚本,而不是一个企业级的python项目,所以它工作得很好。我很好奇,如果这种代码存在于许多人正在使用的大型python项目中,会产生什么后果?这只是一种奇怪的设置变量的方式,当事情基本上不顺利时,很难调试。。。没有太多的安全问题,大多数情况下很难找到问题