I am trying to implement python REPL.
while True:
exec("print repr("+raw_input(">>")+ ")")
Test Outputs:
>>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
Apparently a=3 is evaluated as keyword argument not as assignment operation. so I changed the code as follows
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())
Test Outputs:
>>>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
Is the above code gives the same functionality of python REPL ?