forked from prompt-toolkit/ptpython
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathrepl.py
More file actions
392 lines (315 loc) · 12.8 KB
/
repl.py
File metadata and controls
392 lines (315 loc) · 12.8 KB
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
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
"""
Utility for creating a Python repl.
::
from ptpython.repl import embed
embed(globals(), locals(), vi_mode=False)
"""
import asyncio
import builtins
import os
import sys
import traceback
import warnings
from typing import Any, Callable, ContextManager, Dict, Optional
from prompt_toolkit.document import Document
from prompt_toolkit.formatted_text import (
FormattedText,
PygmentsTokens,
fragment_list_width,
merge_formatted_text,
to_formatted_text,
)
from prompt_toolkit.formatted_text.utils import fragment_list_width
from prompt_toolkit.key_binding.vi_state import InputMode
from prompt_toolkit.patch_stdout import patch_stdout as patch_stdout_context
from prompt_toolkit.shortcuts import clear_title, print_formatted_text, set_title
from prompt_toolkit.utils import DummyContext
from pygments.lexers import PythonLexer, PythonTracebackLexer
from pygments.token import Token
from .eventloop import inputhook
from .python_input import PythonInput
__all__ = ["PythonRepl", "enable_deprecation_warnings", "run_config", "embed"]
class PythonRepl(PythonInput):
def __init__(self, *a, **kw) -> None:
self._startup_paths = kw.pop("startup_paths", None)
super().__init__(*a, **kw)
self._load_start_paths()
self.pt_loop = asyncio.new_event_loop()
def _load_start_paths(self) -> None:
" Start the Read-Eval-Print Loop. "
if self._startup_paths:
for path in self._startup_paths:
if os.path.exists(path):
with open(path, "rb") as f:
code = compile(f.read(), path, "exec")
exec(code, self.get_globals(), self.get_locals())
else:
output = self.app.output
output.write("WARNING | File not found: {}\n\n".format(path))
def run(self) -> None:
# In order to make sure that asyncio code written in the
# interactive shell doesn't interfere with the prompt, we run the
# prompt in a different event loop.
# If we don't do this, people could spawn coroutine with a
# while/true inside which will freeze the prompt.
try:
old_loop: Optional[asyncio.AbstractEventLoop] = asyncio.get_event_loop()
except RuntimeError:
# This happens when the user used `asyncio.run()`.
old_loop = None
asyncio.set_event_loop(self.pt_loop)
try:
return self.pt_loop.run_until_complete(self.run_async())
finally:
# Restore the original event loop.
asyncio.set_event_loop(old_loop)
async def run_async(self) -> None:
if self.terminal_title:
set_title(self.terminal_title)
while True:
# Capture the current input_mode in order to restore it after reset,
# for ViState.reset() sets it to InputMode.INSERT unconditionally and
# doesn't accept any arguments.
def pre_run(
last_input_mode: InputMode = self.app.vi_state.input_mode,
) -> None:
if self.vi_keep_last_used_mode:
self.app.vi_state.input_mode = last_input_mode
if not self.vi_keep_last_used_mode and self.vi_start_in_navigation_mode:
self.app.vi_state.input_mode = InputMode.NAVIGATION
# Run the UI.
try:
text = await self.app.run_async(pre_run=pre_run)
except EOFError:
return
except KeyboardInterrupt:
# Abort - try again.
self.default_buffer.document = Document()
else:
self._process_text(text)
if self.terminal_title:
clear_title()
def _process_text(self, line: str) -> None:
if line and not line.isspace():
try:
# Eval and print.
self._execute(line)
except KeyboardInterrupt as e: # KeyboardInterrupt doesn't inherit from Exception.
self._handle_keyboard_interrupt(e)
except Exception as e:
self._handle_exception(e)
if self.insert_blank_line_after_output:
self.app.output.write("\n")
self.current_statement_index += 1
self.signatures = []
def _execute(self, line: str) -> None:
"""
Evaluate the line and print the result.
"""
output = self.app.output
# WORKAROUND: Due to a bug in Jedi, the current directory is removed
# from sys.path. See: https://github.com/davidhalter/jedi/issues/1148
if "" not in sys.path:
sys.path.insert(0, "")
def compile_with_flags(code: str, mode: str):
" Compile code with the right compiler flags. "
return compile(
code,
"<stdin>",
mode,
flags=self.get_compiler_flags(),
dont_inherit=True,
)
# If the input is single line, remove leading whitespace.
# (This doesn't have to be a syntax error.)
if len(line.splitlines()) == 1:
line = line.strip()
if line.lstrip().startswith("\x1a"):
# When the input starts with Ctrl-Z, quit the REPL.
self.app.exit()
elif line.lstrip().startswith("!"):
# Run as shell command
os.system(line[1:])
else:
# Try eval first
try:
code = compile_with_flags(line, "eval")
result = eval(code, self.get_globals(), self.get_locals())
locals: Dict[str, Any] = self.get_locals()
locals["_"] = locals["_%i" % self.current_statement_index] = result
if result is not None:
out_prompt = to_formatted_text(self.get_output_prompt())
try:
result_str = "%r\n" % (result,)
except UnicodeDecodeError:
# In Python 2: `__repr__` should return a bytestring,
# so to put it in a unicode context could raise an
# exception that the 'ascii' codec can't decode certain
# characters. Decode as utf-8 in that case.
result_str = "%s\n" % repr(result).decode( # type: ignore
"utf-8"
)
# Align every line to the first one.
line_sep = "\n" + " " * fragment_list_width(out_prompt)
result_str = line_sep.join(result_str.splitlines()) + "\n"
# Write output tokens.
if self.enable_syntax_highlighting:
formatted_output = merge_formatted_text(
[
out_prompt,
PygmentsTokens(list(_lex_python_result(result_str))),
]
)
else:
formatted_output = FormattedText(
out_prompt + [("", result_str)]
)
print_formatted_text(
formatted_output,
style=self._current_style,
style_transformation=self.style_transformation,
include_default_pygments_style=False,
output=output,
)
# If not a valid `eval` expression, run using `exec` instead.
except SyntaxError:
code = compile_with_flags(line, "exec")
exec(code, self.get_globals(), self.get_locals())
output.flush()
def _handle_exception(self, e: Exception) -> None:
output = self.app.output
# Instead of just calling ``traceback.format_exc``, we take the
# traceback and skip the bottom calls of this framework.
t, v, tb = sys.exc_info()
# Required for pdb.post_mortem() to work.
sys.last_type, sys.last_value, sys.last_traceback = t, v, tb
tblist = list(traceback.extract_tb(tb))
for line_nr, tb_tuple in enumerate(tblist):
if tb_tuple[0] == "<stdin>":
tblist = tblist[line_nr:]
break
l = traceback.format_list(tblist)
if l:
l.insert(0, "Traceback (most recent call last):\n")
l.extend(traceback.format_exception_only(t, v))
tb_str = "".join(l)
# Format exception and write to output.
# (We use the default style. Most other styles result
# in unreadable colors for the traceback.)
if self.enable_syntax_highlighting:
tokens = list(_lex_python_traceback(tb_str))
else:
tokens = [(Token, tb_str)]
print_formatted_text(
PygmentsTokens(tokens),
style=self._current_style,
style_transformation=self.style_transformation,
include_default_pygments_style=False,
output=output,
)
output.write("%s\n" % e)
output.flush()
def _handle_keyboard_interrupt(self, e: KeyboardInterrupt) -> None:
output = self.app.output
output.write("\rKeyboardInterrupt\n\n")
output.flush()
def _lex_python_traceback(tb):
" Return token list for traceback string. "
lexer = PythonTracebackLexer()
return lexer.get_tokens(tb)
def _lex_python_result(tb):
" Return token list for Python string. "
lexer = PythonLexer()
return lexer.get_tokens(tb)
def enable_deprecation_warnings() -> None:
"""
Show deprecation warnings, when they are triggered directly by actions in
the REPL. This is recommended to call, before calling `embed`.
e.g. This will show an error message when the user imports the 'sha'
library on Python 2.7.
"""
warnings.filterwarnings("default", category=DeprecationWarning, module="__main__")
def run_config(repl: PythonInput, config_file: str = "~/.ptpython/config.py") -> None:
"""
Execute REPL config file.
:param repl: `PythonInput` instance.
:param config_file: Path of the configuration file.
"""
# Expand tildes.
config_file = os.path.expanduser(config_file)
def enter_to_continue() -> None:
input("\nPress ENTER to continue...")
# Check whether this file exists.
if not os.path.exists(config_file):
print("Impossible to read %r" % config_file)
enter_to_continue()
return
# Run the config file in an empty namespace.
try:
namespace: Dict[str, Any] = {}
with open(config_file, "rb") as f:
code = compile(f.read(), config_file, "exec")
exec(code, namespace, namespace)
# Now we should have a 'configure' method in this namespace. We call this
# method with the repl as an argument.
if "configure" in namespace:
namespace["configure"](repl)
except Exception:
traceback.print_exc()
enter_to_continue()
def embed(
globals=None,
locals=None,
configure: Optional[Callable[[PythonRepl], None]] = None,
vi_mode: bool = False,
history_filename: Optional[str] = None,
title: Optional[str] = None,
startup_paths=None,
patch_stdout: bool = False,
return_asyncio_coroutine: bool = False,
) -> None:
"""
Call this to embed Python shell at the current point in your program.
It's similar to `IPython.embed` and `bpython.embed`. ::
from prompt_toolkit.contrib.repl import embed
embed(globals(), locals())
:param vi_mode: Boolean. Use Vi instead of Emacs key bindings.
:param configure: Callable that will be called with the `PythonRepl` as a first
argument, to trigger configuration.
:param title: Title to be displayed in the terminal titlebar. (None or string.)
"""
# Default globals/locals
if globals is None:
globals = {
"__name__": "__main__",
"__package__": None,
"__doc__": None,
"__builtins__": builtins,
}
locals = locals or globals
def get_globals():
return globals
def get_locals():
return locals
# Create REPL.
repl = PythonRepl(
get_globals=get_globals,
get_locals=get_locals,
vi_mode=vi_mode,
history_filename=history_filename,
startup_paths=startup_paths,
)
if title:
repl.terminal_title = title
if configure:
configure(repl)
# Start repl.
patch_context: ContextManager = patch_stdout_context() if patch_stdout else DummyContext()
if return_asyncio_coroutine:
async def coroutine():
with patch_context:
await repl.run_async()
return coroutine()
else:
with patch_context:
repl.run()