Created
December 22, 2018 15:07
-
-
Save rtaycher/36b6ebef206f69e8c9ddfefc2e466530 to your computer and use it in GitHub Desktop.
Simple read eval print loop for python
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
PROMPT = 'INPUT CODE > ' | |
PROMPT_SIMPLE = ' > ' | |
def eval_code(code): | |
was_expression = True | |
try: | |
try: | |
return eval(code, locals(), globals()), was_expression | |
except SyntaxError: | |
try: | |
exec(code, locals(), globals()) | |
except SyntaxError as ex: | |
print('bad syntax.\n', 'code:\n', code + '\n', ex) | |
return None, False | |
was_expression = False | |
return None, was_expression | |
except Exception as ex: | |
print('eval caused an exception.\n', 'code:\n', code + '\n', ex) | |
return None, False | |
def read(): | |
code = '' | |
line = input(PROMPT).rstrip() | |
code += line | |
if line[-1] == ':' : | |
line = input(PROMPT_SIMPLE) | |
while line and line[0] in [' ', '\t']: | |
code += '\n' + line | |
line = input(PROMPT_SIMPLE) | |
return code | |
while True: | |
code = read() | |
result, was_expression = eval_code(code) | |
if was_expression: | |
print(repr(result)) | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment