0
# Jupyter Notebook Integration
1
2
Specialized spinner implementation for Jupyter notebooks and IPython environments using widgets. HaloNotebook provides the same API as the standard Halo class but renders using IPython display widgets instead of terminal output.
3
4
## Capabilities
5
6
### HaloNotebook Class
7
8
Jupyter-optimized spinner that inherits from Halo with widget-based rendering for notebook environments.
9
10
```python { .api }
11
class HaloNotebook(Halo):
12
def __init__(
13
self,
14
text="",
15
color="cyan",
16
text_color=None,
17
spinner=None,
18
placement="left",
19
animation=None,
20
interval=-1,
21
enabled=True,
22
stream=sys.stdout
23
):
24
"""
25
Initialize a Jupyter notebook-compatible spinner.
26
27
Parameters: Same as Halo.__init__
28
- text (str): Text to display alongside spinner (default: "")
29
- color (str): Spinner color (default: "cyan")
30
- text_color (str): Text color (default: None)
31
- spinner (str|dict): Spinner type or custom definition (default: "dots")
32
- placement (str): Spinner position - "left" or "right" (default: "left")
33
- animation (str): Text animation - "bounce", "marquee" (default: None)
34
- interval (int): Frame interval in milliseconds (default: -1)
35
- enabled (bool): Whether spinner is active (default: True)
36
- stream (io.TextIOWrapper): Output stream (default: sys.stdout)
37
"""
38
```
39
40
### Widget Output Management
41
42
HaloNotebook uses IPython widgets for rendering, providing clean output management in notebook cells.
43
44
```python { .api }
45
@property
46
def output(self):
47
"""
48
Get the IPython Output widget instance.
49
50
Returns:
51
- ipywidgets.Output: The widget used for spinner display
52
"""
53
```
54
55
**Usage Example:**
56
57
```python
58
# In Jupyter notebook cell
59
from halo import HaloNotebook
60
import time
61
62
# Basic usage - identical to Halo
63
spinner = HaloNotebook(text='Processing data', spinner='dots', color='blue')
64
spinner.start()
65
time.sleep(3)
66
spinner.succeed('✓ Processing complete')
67
```
68
69
### Environment Detection
70
71
Halo automatically detects the execution environment and uses appropriate spinner class.
72
73
```python
74
from halo import Halo
75
import time
76
77
# Automatically uses HaloNotebook in Jupyter, regular Halo in terminal
78
with Halo(text='Loading', spinner='dots'):
79
time.sleep(2)
80
```
81
82
## Installation for Notebook Support
83
84
For full Jupyter notebook support, install with notebook dependencies:
85
86
```bash
87
pip install halo[ipython]
88
```
89
90
This installs the required IPython and ipywidgets dependencies:
91
- `IPython==5.7.0`
92
- `ipywidgets==7.1.0`
93
94
## Usage Patterns
95
96
### Basic Notebook Usage
97
98
```python
99
# In Jupyter notebook cell
100
from halo import HaloNotebook
101
import time
102
103
# Context manager usage
104
with HaloNotebook(text='Training model', spinner='dots', color='green'):
105
# Simulate long-running operation
106
for epoch in range(5):
107
time.sleep(1)
108
print(f"Epoch {epoch + 1} completed") # This won't interfere with spinner
109
110
print("Training completed!")
111
```
112
113
### Manual Control in Notebooks
114
115
```python
116
# In Jupyter notebook cell
117
from halo import HaloNotebook
118
import time
119
120
spinner = HaloNotebook(text='Starting analysis', spinner='star')
121
spinner.start()
122
123
# Update text during execution
124
for i in range(1, 6):
125
spinner.text = f'Processing batch {i}/5'
126
time.sleep(1)
127
128
spinner.succeed('✓ Analysis completed successfully')
129
```
130
131
### Decorator Usage in Notebooks
132
133
```python
134
# In Jupyter notebook cell
135
from halo import HaloNotebook
136
import time
137
138
@HaloNotebook(text='Running computation', spinner='dots', color='cyan')
139
def heavy_computation():
140
time.sleep(3)
141
return "computation_result"
142
143
result = heavy_computation()
144
print(f"Result: {result}")
145
```
146
147
### Status Methods in Notebooks
148
149
```python
150
# In Jupyter notebook cell
151
from halo import HaloNotebook
152
import time
153
154
def analyze_data():
155
spinner = HaloNotebook(text='Analyzing dataset', spinner='arrow')
156
spinner.start()
157
158
time.sleep(2)
159
160
# Different completion methods work the same
161
try:
162
# Simulate analysis
163
success = True
164
if success:
165
spinner.succeed('✓ Analysis completed - 1000 records processed')
166
else:
167
spinner.fail('✗ Analysis failed')
168
except Exception as e:
169
spinner.fail(f'✗ Error during analysis: {e}')
170
171
analyze_data()
172
```
173
174
## Advanced Notebook Features
175
176
### Multiple Spinners in Sequence
177
178
```python
179
# In Jupyter notebook cell
180
from halo import HaloNotebook
181
import time
182
183
def data_pipeline():
184
# Step 1: Data loading
185
loader = HaloNotebook(text='Loading data', spinner='dots', color='blue')
186
loader.start()
187
time.sleep(1)
188
loader.succeed('✓ Data loaded - 10,000 records')
189
190
# Step 2: Data processing
191
processor = HaloNotebook(text='Processing data', spinner='star', color='green')
192
processor.start()
193
time.sleep(2)
194
processor.succeed('✓ Data processed - features extracted')
195
196
# Step 3: Model training
197
trainer = HaloNotebook(text='Training model', spinner='arrow', color='red')
198
trainer.start()
199
time.sleep(3)
200
trainer.succeed('✓ Model trained - accuracy: 95.2%')
201
202
data_pipeline()
203
```
204
205
### Progress Tracking
206
207
```python
208
# In Jupyter notebook cell
209
from halo import HaloNotebook
210
import time
211
212
def process_files():
213
files = ['data1.csv', 'data2.csv', 'data3.csv', 'data4.csv', 'data5.csv']
214
215
spinner = HaloNotebook(text='Starting file processing', spinner='dots')
216
spinner.start()
217
218
for i, file in enumerate(files, 1):
219
spinner.text = f'Processing {file} ({i}/{len(files)})'
220
time.sleep(1) # Simulate processing time
221
222
spinner.succeed(f'✓ Processed {len(files)} files successfully')
223
224
process_files()
225
```
226
227
### Integration with Pandas/NumPy Operations
228
229
```python
230
# In Jupyter notebook cell
231
from halo import HaloNotebook
232
import pandas as pd
233
import numpy as np
234
import time
235
236
def data_analysis():
237
spinner = HaloNotebook(text='Loading dataset', spinner='dots', color='blue')
238
spinner.start()
239
240
# Simulate data loading
241
time.sleep(1)
242
data = pd.DataFrame(np.random.randn(10000, 5))
243
244
spinner.text = 'Computing statistics'
245
time.sleep(1)
246
stats = data.describe()
247
248
spinner.text = 'Performing correlation analysis'
249
time.sleep(1)
250
corr = data.corr()
251
252
spinner.succeed('✓ Analysis complete - results ready')
253
254
return stats, corr
255
256
stats, correlations = data_analysis()
257
```
258
259
## Environment Considerations
260
261
### Automatic Environment Detection
262
263
Halo automatically detects the execution environment:
264
265
```python
266
from halo._utils import get_environment
267
268
env = get_environment()
269
print(f"Current environment: {env}")
270
# Possible values: "terminal", "ipython", "jupyter"
271
```
272
273
### Manual Environment Selection
274
275
```python
276
# Force use of HaloNotebook even in terminal (not recommended)
277
from halo import HaloNotebook
278
279
# Force use of regular Halo in notebook (will not display properly)
280
from halo.halo import Halo
281
```
282
283
### Widget Display Requirements
284
285
For HaloNotebook to work properly:
286
287
1. **IPython/Jupyter environment**: Must be running in IPython or Jupyter
288
2. **Widget support**: Jupyter must support widget display
289
3. **Dependencies installed**: ipywidgets must be available
290
291
If these requirements aren't met, HaloNotebook will fall back to standard Halo behavior.
292
293
## Troubleshooting
294
295
### Common Issues
296
297
**Spinner not displaying in notebook:**
298
- Ensure `ipywidgets` is installed: `pip install ipywidgets`
299
- Enable widgets: `jupyter nbextension enable --py widgetsnbextension`
300
301
**Multiple outputs in cell:**
302
- Use `HaloNotebook` instead of `Halo` in notebook environments
303
- Avoid mixing print statements with active spinners
304
305
**Widget state errors:**
306
- Restart notebook kernel if widgets become unresponsive
307
- Each spinner creates a new widget instance