我遇到了一个问题exec
在处理代码的组合字符串时,它返回了一个错误:函数“python”中的unqualified 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()
但是在代码中不应该指定
locals()
,除非您想让用户访问在python
函数中定义的局部变量。你知道吗而且,转换循环结束得太早,应该
for x in range(1, lines + 1):
下面是一个经过编辑的代码版本,它可以满足您的需要:
下面是代码的另一个版本,它不会将每一行作为新变量存储在
globals()
import readline
语句可以进行行编辑;但是IIRC在Windows中不起作用。你知道吗相关问题 更多 >
编程相关推荐