几分钟的修改让我在 Python 2.7 中得到了这个 Read-Eval-Print Loop:
#!/usr/bin/env python
import code
import sys
LINE_NUMBER=0
def reset_linenum():
global LINE_NUMBER
LINE_NUMBER=-1
def resettable_REPL():
global LINE_NUMBER
BUFFERED_LINES=[]
ii=code.InteractiveInterpreter({"reset_linenum":reset_linenum})
while True:
try:
BUFFERED_LINES.append(raw_input("!"+sys.ps1)+'\n')
while (BUFFERED_LINES[-1][:1] in " \t" or
ii.runsource("\n"*LINE_NUMBER+"".join(BUFFERED_LINES), "console")):
BUFFERED_LINES.append(raw_input("!"+sys.ps2)+'\n')
LINE_NUMBER+=len(BUFFERED_LINES)
BUFFERED_LINES=[]
except EOFError:
break
if __name__=='__main__':
resettable_REPL()
这有点骇人听闻,但它会在会话继续时跟踪行号,并允许通过调用来重置当前计数reset_linenum()
。一个示例会话:
!!!> print "hello" # line 1
hello
!!!> def badfunc(): # line 2
!... raise Exception("doh") # line 3
!!!> badfunc() # line 4
Traceback (most recent call last):
File "console", line 4, in <module>
File "console", line 3, in badfunc
Exception: doh
!!!> ? # line 5
File "console", line 5
?
^
SyntaxError: invalid syntax
!!!> reset_linenum() # RESET
!!!> raise Exception("!") # line 1
Traceback (most recent call last):
File "console", line 1, in <module>
Exception: !
!!!>
编辑:修复了 REPL 不会过早地执行缩进块。