我正在尝试实现python REPL。
while True:
exec("print repr("+raw_input(">>")+ ")")
测试输出:
>>1+1
2
>>"foo "+"bar"
'foo bar'
>>a=3
Traceback (most recent call last):
File "/Users/user/Projects/python/custom_interpreter.py", line 2, in <module>
exec("print repr("+raw_input(">>")+ ")")
File "<string>", line 1, in <module>
TypeError: repr() takes no keyword argument
显然a = 3被评估为关键字参数而不是赋值操作。所以我改变了代码如下
import traceback
import sys
while True:
cmd = raw_input(">>>")
try:
exec "print repr("+ cmd + ")"
except TypeError:
try:
exec cmd
except Exception as e:
sys.stdout.write(traceback.format_exc())
except Exception as e:
sys.stdout.write(traceback.format_exc())
测试输出:
>>>a=1
>>>a
1
>>>b=2
>>>b+a
3
>>>"foo "+"bar"
'foo bar'
>>>"foo "+1
Traceback (most recent call last):
File "/Users/user/Projects/spoj/python/MIXTURES/stack.py", line 9, in <module>
exec cmd
File "<string>", line 1, in <module>
TypeError: cannot concatenate 'str' and 'int' objects
>>>exit()
Process finished with exit code 0
上面的代码是否提供了与python REPL相同的功能?