【发布时间】:2010-10-26 16:37:12
【问题描述】:
我想执行一些 Python 代码,在运行时输入,所以我得到字符串并调用
exec(pp, globals(), locals())
其中 pp 是字符串。它工作正常,除了递归调用,例如。 g.例如,这段代码是可以的:
def horse():
robot.step()
robot.step()
robot.turn(-1)
robot.step()
while True:
horse()
但这个不是:
def horse():
robot.step()
robot.step()
robot.turn(-1)
robot.step()
horse()
horse()
NameError: 全局名称 'horse' 不是 定义
有没有办法运行递归代码?
更新
a = """\
def rec(n):
if n > 10:
return
print n
return rec(n+1)
rec(5)"""
exec(a)
如果放在顶层就可以了。但如果在函数内部移动:
def fn1():
a = """\
def rec(n):
if n > 10:
return
print n
return rec(n+1)
rec(5)"""
exec(a)
fn1()
同样的错误发生:NameError: global name 'rec' is not defined
【问题讨论】:
-
请告诉我这个执行字符串不是来自用户输入。