-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathpython-interpret
executable file
·46 lines (37 loc) · 1.29 KB
/
python-interpret
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
#!/usr/bin/env python3.6
# Simulate running code at a python prompt
#
# Separate statements by two newlines
# they will be stripped on output,
# but are used to parse out distinct statements
import io
import re
import sys
import time
import tokenize
# Not used by this script, but allows snippets to skip the import
from tempfile import TemporaryDirectory
try:
last_t_type = None
code_tokens = []
for t in tokenize.generate_tokens(sys.stdin.readline):
if len(code_tokens) == 0 and t.type == tokenize.DEDENT:
continue
code_tokens.append(t)
if ((t.type == tokenize.NL and t.type == last_t_type)
or t.type == tokenize.ENDMARKER):
code = tokenize.untokenize(code_tokens)
code = re.sub(r"^\\\n", "", code, flags=re.MULTILINE)
code = code.strip("\n")
print("\n".join(">>> " + s for s in code.split("\n")))
compiled_code = compile(code, '', 'single')
ret = exec(compiled_code, symbol_table)
code_tokens = []
last_t_type = t.type
except Exception as e:
with open('python-interpret.err', 'w') as out:
out.write(f"Caught exception {e} with tokens:\n")
for t in code_tokens:
out.write(repr(t) + "\n")
out.write("\n")
raise