我遇到问题exec
代码的组合字符串,它返回错误:函数中的非限定exec' 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):
y=x+1
fullcode+=globals() ['line%s' %x] + enter
try:
exec fullcode
except:
print "Error"
python()
答案 0 :(得分:0)
为什么你这样直接操纵globals()
字典?
无论如何,您需要提供exec
工作环境。完整的表格是
exec fullcode in globals(), locals()
但在您的代码中,除非您希望授予用户访问locals()
函数中定义的局部变量的权限,否则不应指定python
。
此外,您的转化循环过早结束,应该是
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中不起作用。