0
# Core Shell Functions
1
2
Primary entry points for starting IPython sessions, embedding interactive shells in existing code for debugging, and managing the current IPython instance. These functions provide the foundation for IPython's interactive computing capabilities.
3
4
## Capabilities
5
6
### Starting IPython Sessions
7
8
Launch a complete IPython session with full initialization, configuration loading, and startup file execution.
9
10
```python { .api }
11
def start_ipython(argv=None, **kwargs):
12
"""
13
Launch a normal IPython instance (as opposed to embedded).
14
15
IPython.embed() puts a shell in a particular calling scope,
16
such as a function or method for debugging purposes,
17
which is often not desirable.
18
19
start_ipython() does full, regular IPython initialization,
20
including loading startup files, configuration, etc.
21
much of which is skipped by embed().
22
23
Parameters:
24
- argv: list or None, optional - Command-line options. If None,
25
IPython will parse from sys.argv. Pass [] to prevent parsing.
26
- user_ns: dict, optional - Initialize IPython user namespace
27
- **kwargs: various, optional - Additional Application constructor args,
28
such as 'config' (traitlets Config object)
29
30
Returns:
31
TerminalIPythonApp instance
32
"""
33
```
34
35
Usage example:
36
37
```python
38
import IPython
39
40
# Start with default configuration
41
IPython.start_ipython()
42
43
# Start without command-line parsing
44
IPython.start_ipython(argv=[])
45
46
# Start with custom user namespace
47
IPython.start_ipython(user_ns={'custom_var': 42})
48
49
# Start with configuration
50
from traitlets.config import Config
51
c = Config()
52
c.TerminalInteractiveShell.colors = 'Linux'
53
IPython.start_ipython(config=c)
54
```
55
56
### Embedding IPython Shells
57
58
Embed an IPython shell within existing code for interactive debugging and exploration.
59
60
```python { .api }
61
def embed(header='', compile_flags=None, **kwargs):
62
"""
63
Call this to embed IPython at the current point in your program.
64
65
The first invocation of this will create an InteractiveShellEmbed
66
instance and then call it. Consecutive calls just call the already
67
created instance.
68
69
Parameters:
70
- header: str, optional - Custom header message to display
71
- compile_flags: int, optional - Python compile flags
72
- **kwargs: various, optional - Additional arguments passed to
73
InteractiveShellEmbed constructor
74
75
Returns:
76
None
77
"""
78
```
79
80
Usage example:
81
82
```python
83
import IPython
84
85
def debug_function(data):
86
processed = []
87
for item in data:
88
# Drop into IPython for debugging
89
IPython.embed(header="Debug point - inspect 'item' and 'processed'")
90
result = complex_processing(item)
91
processed.append(result)
92
return processed
93
94
# When called, this will pause execution and open IPython shell
95
debug_function([1, 2, 3, 4, 5])
96
```
97
98
### Getting Current IPython Instance
99
100
Retrieve the currently running IPython instance to programmatically interact with the shell.
101
102
```python { .api }
103
def get_ipython():
104
"""
105
Get the currently running InteractiveShell instance.
106
107
This function is meant for use within IPython code or code that
108
runs within an IPython session. It provides access to the current
109
shell instance for programmatic interaction.
110
111
Returns:
112
InteractiveShell instance or None if not running in IPython
113
"""
114
```
115
116
Usage example:
117
118
```python
119
import IPython
120
121
# Check if running in IPython
122
ipython = IPython.get_ipython()
123
if ipython is not None:
124
# Execute code programmatically
125
ipython.run_cell("x = 42")
126
127
# Access shell features
128
ipython.magic('ls') # Run magic command
129
130
# Get user namespace
131
user_vars = ipython.user_ns
132
print(f"Available variables: {list(user_vars.keys())}")
133
134
# Run code with custom namespace
135
result = ipython.run_cell("print(f'x = {x}')", store_history=False)
136
else:
137
print("Not running in IPython")
138
```
139
140
### Kernel Embedding (Deprecated)
141
142
Legacy function for embedding IPython kernels (deprecated in favor of ipykernel).
143
144
```python { .api }
145
def embed_kernel(module=None, local_ns=None, **kwargs):
146
"""
147
Embed and start an IPython kernel in a given scope.
148
149
This is a deprecated alias for ipykernel.embed.embed_kernel(),
150
to be removed in the future. Import directly from ipykernel.embed.
151
152
Parameters:
153
- module: types.ModuleType, optional - Module to load into IPython globals
154
- local_ns: dict, optional - Namespace to load into IPython user namespace
155
- **kwargs: various, optional - Arguments for IPKernelApp constructor
156
157
Returns:
158
None
159
"""
160
```
161
162
## Types
163
164
```python { .api }
165
class InteractiveShell:
166
"""
167
Core interactive shell implementation providing execution environment,
168
history management, completion, and object introspection.
169
"""
170
171
def run_cell(self, raw_cell, store_history=True, silent=False, shell_futures=True):
172
"""
173
Execute a code cell.
174
175
Parameters:
176
- raw_cell: str - Code to execute
177
- store_history: bool - Whether to store in history
178
- silent: bool - Whether to suppress output
179
- shell_futures: bool - Whether to return ExecutionResult
180
181
Returns:
182
ExecutionResult object
183
"""
184
185
def complete(self, text, line=None, cursor_pos=None):
186
"""
187
Perform tab completion on text.
188
189
Parameters:
190
- text: str - Text to complete
191
- line: str, optional - Full line of text
192
- cursor_pos: int, optional - Cursor position
193
194
Returns:
195
tuple: (text, matches) where matches is list of completions
196
"""
197
198
def object_inspect(self, oname, detail_level=0):
199
"""
200
Get information about an object.
201
202
Parameters:
203
- oname: str - Object name
204
- detail_level: int - Level of detail (0 or 1)
205
206
Returns:
207
dict: Object information
208
"""
209
210
class TerminalInteractiveShell(InteractiveShell):
211
"""
212
Terminal-based interactive shell with advanced terminal features
213
including syntax highlighting, keyboard shortcuts, and history.
214
"""
215
216
def __init__(self, **kwargs):
217
"""Initialize terminal shell with configuration."""
218
```