我在exec
处理代码的组合字符串时遇到问题,它返回错误:函数'python'中的不合格exec它是嵌套函数
有时,它不会返回错误,而是导致没有任何输出。
def python():
prompt=">>> "
lines=0
fullcode=""
enter="n"
print "nPython 2.7.8"
print "nEnter your lines of code, when you are finished enter 'end'."
for x in range(1,1000):
code=raw_input(prompt)
if "end" not in code.lower():
globals()['line%s' % x] = code
lines+=1
else:
break
for x in range(1,lines):
y=x+1
fullcode+=globals() ['line%s' %x] + enter
try:
exec fullcode
except:
print "Error"
python()
为什么要这样直接操作globals()
dict?
无论如何,你需要为exec
提供一个工作的上下文
exec fullcode in globals(), locals()
但在代码中,除非您想让用户访问python
函数中定义的局部变量,否则不应该指定locals()
。
此外,您的转换循环结束得太早,应该是
for x in range(1, lines + 1):
这是一个经过编辑的代码版本,应该可以做你想做的事情:
#! /usr/bin/env python
def python():
prompt=">>> "
lines=0
fullcode=""
enter="n"
print "nPython 2.7.8"
print "nEnter your lines of code, when you are finished enter 'end'."
for x in range(1,1000):
code=raw_input(prompt)
if "end" not in code.lower():
globals()['line%s' % x] = code
lines+=1
else:
break
for x in range(1,lines+1):
fullcode+=globals()['line%s' %x] + enter
try:
exec fullcode in globals() #, locals()
except Exception, e:
print "Error:", e
python()
这里有一个代码的替代版本,它不会将每一行都存储为globals()
中的一个新变量
#! /usr/bin/env python
import readline
def python():
prompt = ">>> "
codelines = []
print "nPython 2.7.8"
print "nEnter your lines of code, when you are finished enter 'end'."
while True:
code = raw_input(prompt)
if "end" not in code.lower():
codelines.append(code)
else:
break
fullcode = 'n'.join(codelines)
#print `fullcode`
try:
exec fullcode #in globals(), locals()
except Exception, e:
print "Error:", e
python()
import readline
语句为您提供行编辑功能;但IIRC在Windows中不起作用。