Skip to content

Instantly share code, notes, and snippets.

@rtaycher
Created December 22, 2018 15:07
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save rtaycher/36b6ebef206f69e8c9ddfefc2e466530 to your computer and use it in GitHub Desktop.
Save rtaycher/36b6ebef206f69e8c9ddfefc2e466530 to your computer and use it in GitHub Desktop.
Simple read eval print loop for python
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