0
# Terminal Interface and Embedding
1
2
Advanced terminal integration with syntax highlighting, tab completion, keyboard shortcuts, and embedding capabilities for interactive debugging. IPython provides rich terminal experiences and flexible embedding options for development workflows.
3
4
## Capabilities
5
6
### Terminal Interactive Shell
7
8
Advanced terminal-based interactive shell with rich features.
9
10
```python { .api }
11
class TerminalInteractiveShell(InteractiveShell):
12
"""
13
Terminal-based interactive shell with advanced terminal features.
14
15
Provides syntax highlighting, keyboard shortcuts, multi-line editing,
16
history navigation, and tab completion in terminal environments.
17
"""
18
19
def __init__(self, **kwargs):
20
"""
21
Initialize terminal shell.
22
23
Parameters include configuration for colors, prompts, completion,
24
history, and other terminal-specific features.
25
"""
26
27
def interact(self):
28
"""Start the interactive terminal loop."""
29
30
def mainloop(self):
31
"""Main event loop for terminal interaction."""
32
```
33
34
### Embedding Interactive Shells
35
36
Embed IPython shells within existing applications and code for debugging.
37
38
```python { .api }
39
def embed(header='', compile_flags=None, **kwargs):
40
"""
41
Call this to embed IPython at the current point in your program.
42
43
Creates an interactive IPython shell that has access to the local
44
namespace where embed() is called. Useful for debugging and
45
interactive exploration of program state.
46
47
Parameters:
48
- header: str, optional - Custom header message
49
- compile_flags: int, optional - Python compile flags
50
- **kwargs: additional arguments for InteractiveShellEmbed
51
52
Returns:
53
None
54
"""
55
56
class InteractiveShellEmbed(TerminalInteractiveShell):
57
"""
58
Interactive shell for embedding within other applications.
59
60
Specialized shell that can be embedded in existing code,
61
providing access to local variables and enabling interactive
62
debugging and exploration.
63
"""
64
65
def __init__(self, **kwargs):
66
"""Initialize embedded shell."""
67
68
def __call__(self, header='', local_ns=None, module=None, **kwargs):
69
"""Activate the embedded shell."""
70
71
class EmbeddedMagics(Magics):
72
"""Magic commands specific to embedded shells."""
73
74
@line_magic
75
def kill_embedded(self, parameter_s=''):
76
"""Exit embedded shell and kill the embedded context."""
77
78
@line_magic
79
def exit_raise(self, parameter_s=''):
80
"""Exit embedded shell by raising SystemExit."""
81
```
82
83
Usage examples:
84
85
```python
86
# Basic embedding for debugging
87
import IPython
88
89
def process_data(data):
90
processed = []
91
for i, item in enumerate(data):
92
# Debug specific iterations
93
if i == 5:
94
IPython.embed(header=f"Debugging iteration {i}")
95
96
result = complex_operation(item)
97
processed.append(result)
98
99
return processed
100
101
# Conditional embedding
102
import IPython
103
104
def analyze_results(results):
105
suspicious_results = [r for r in results if r.confidence < 0.5]
106
107
if suspicious_results:
108
print(f"Found {len(suspicious_results)} suspicious results")
109
IPython.embed(header="Debug suspicious results - check 'suspicious_results' variable")
110
111
return results
112
113
# Custom embedded shell configuration
114
from IPython.terminal.embed import InteractiveShellEmbed
115
116
# Create custom embedded shell
117
ipshell = InteractiveShellEmbed(
118
banner1="Custom Debug Shell\n",
119
exit_msg="Leaving debug mode"
120
)
121
122
def debug_function():
123
local_var = "debug data"
124
ipshell(header="Custom shell active", local_ns=locals())
125
```
126
127
### Keyboard Shortcuts and Terminal Features
128
129
Terminal customization and keyboard shortcut management.
130
131
```python { .api }
132
def create_ipython_shortcuts(shell):
133
"""
134
Create IPython-specific keyboard shortcuts for terminal interface.
135
136
Parameters:
137
- shell: TerminalInteractiveShell instance
138
139
Returns:
140
KeyBindings object with IPython shortcuts
141
"""
142
143
# Common terminal features and shortcuts:
144
# Ctrl+D: Exit IPython
145
# Ctrl+C: Interrupt execution
146
# Ctrl+L: Clear screen
147
# Ctrl+A: Move to beginning of line
148
# Ctrl+E: Move to end of line
149
# Ctrl+K: Kill to end of line
150
# Ctrl+U: Kill to beginning of line
151
# Ctrl+R: Reverse history search
152
# Tab: Code completion
153
# Shift+Tab: Show docstring
154
# Up/Down: History navigation
155
# Ctrl+P/Ctrl+N: History navigation (alternative)
156
```
157
158
### Terminal Application Framework
159
160
Framework for building terminal-based IPython applications.
161
162
```python { .api }
163
class TerminalIPythonApp(BaseIPythonApplication):
164
"""
165
Terminal IPython application.
166
167
Main application class for running IPython in terminal mode.
168
Handles configuration, initialization, and application lifecycle.
169
"""
170
171
def initialize(self, argv=None):
172
"""Initialize the application with command-line arguments."""
173
174
def start(self):
175
"""Start the IPython terminal application."""
176
177
def launch_new_instance(argv=None, **kwargs):
178
"""
179
Launch a new IPython terminal instance.
180
181
Parameters:
182
- argv: list, optional - Command-line arguments
183
- **kwargs: additional application arguments
184
185
Returns:
186
TerminalIPythonApp instance
187
"""
188
```
189
190
### Terminal Customization
191
192
Configuration options for terminal appearance and behavior.
193
194
```python { .api }
195
# Terminal color schemes
196
# Available schemes: 'NoColor', 'Linux', 'Neutral'
197
ipython.colors = 'Linux'
198
199
# Prompt customization
200
ipython.prompt_in1 = 'In [\\#]: '
201
ipython.prompt_in2_template = ' .\\D.: '
202
ipython.prompt_out_template = 'Out[\\#]: '
203
204
# History configuration
205
ipython.history_length = 10000
206
ipython.history_load_length = 1000
207
208
# Completion configuration
209
ipython.readline_use = True
210
ipython.readline_omit__names = 2
211
212
# Auto-indentation
213
ipython.autoindent = True
214
215
# Syntax highlighting
216
ipython.highlighting_style = 'default' # or 'emacs', 'vim', etc.
217
```
218
219
Terminal usage examples:
220
221
```python
222
# Start IPython with custom configuration
223
import IPython
224
from traitlets.config import Config
225
226
c = Config()
227
c.TerminalInteractiveShell.colors = 'Linux'
228
c.TerminalInteractiveShell.autoindent = True
229
c.TerminalInteractiveShell.history_length = 5000
230
231
IPython.start_ipython(config=c)
232
233
# Advanced embedding with context management
234
class DebugContext:
235
def __init__(self, name):
236
self.name = name
237
238
def __enter__(self):
239
print(f"Entering debug context: {self.name}")
240
return self
241
242
def __exit__(self, exc_type, exc_val, exc_tb):
243
print(f"Exiting debug context: {self.name}")
244
245
def embed(self, **kwargs):
246
IPython.embed(header=f"Debug: {self.name}", **kwargs)
247
248
# Usage
249
with DebugContext("data_processing") as debug:
250
data = process_complex_data()
251
if data is None:
252
debug.embed() # Drop into shell for debugging
253
```
254
255
## Types
256
257
```python { .api }
258
class TerminalInteractiveShell(InteractiveShell):
259
"""
260
Terminal-based interactive shell.
261
262
Extends InteractiveShell with terminal-specific features like
263
syntax highlighting, keyboard shortcuts, and prompt formatting.
264
"""
265
266
def __init__(self, **kwargs):
267
"""Initialize with terminal-specific configuration."""
268
269
def interact(self):
270
"""Start interactive terminal session."""
271
272
def prompt_for_code(self):
273
"""Display prompt and read code input."""
274
275
class InteractiveShellEmbed(TerminalInteractiveShell):
276
"""
277
Embeddable interactive shell.
278
279
Shell that can be embedded in existing applications,
280
providing access to local namespace and debugging capabilities.
281
"""
282
283
def __call__(self, header='', local_ns=None, module=None, **kwargs):
284
"""Activate embedded shell in current context."""
285
286
class TerminalIPythonApp(BaseIPythonApplication):
287
"""
288
Terminal IPython application.
289
290
Main application for running IPython in terminal mode,
291
handling configuration and application lifecycle.
292
"""
293
294
def initialize(self, argv=None):
295
"""Initialize application."""
296
297
def start(self):
298
"""Start terminal application."""
299
300
# Configuration classes
301
class TerminalInteractiveShellConfig:
302
"""Configuration for terminal shell features."""
303
colors = 'Linux' # Color scheme
304
autoindent = True # Auto-indentation
305
history_length = 10000 # History size
306
completion_use_history = True # Use history for completion
307
```