0
# Client Communication
1
2
Kernel communication clients for executing code, sending messages, and receiving results from Jupyter kernels. Provides both blocking and asynchronous interfaces for different usage patterns and integration scenarios.
3
4
## Capabilities
5
6
### Base Kernel Client
7
8
The `KernelClient` class provides the foundational API for communicating with kernels via ZMQ channels, including code execution, completion, inspection, and other kernel services.
9
10
```python { .api }
11
class KernelClient:
12
"""Base class for communicating with a kernel via ZMQ channels."""
13
14
def execute(self, code, silent=False, store_history=True,
15
user_expressions=None, allow_stdin=None, stop_on_error=True):
16
"""
17
Execute code in the kernel.
18
19
Parameters:
20
- code (str): Code to execute
21
- silent (bool): Don't display output if True
22
- store_history (bool): Store in execution history if True
23
- user_expressions (dict): Expressions to evaluate
24
- allow_stdin (bool): Allow stdin requests from kernel
25
- stop_on_error (bool): Stop execution on first error
26
27
Returns:
28
str: Message ID for tracking the request
29
"""
30
31
def complete(self, code, cursor_pos=None):
32
"""
33
Request tab completion from kernel.
34
35
Parameters:
36
- code (str): Code to complete
37
- cursor_pos (int): Cursor position in code
38
39
Returns:
40
str: Message ID for tracking the request
41
"""
42
43
def inspect(self, code, cursor_pos=None, detail_level=0):
44
"""
45
Request object inspection from kernel.
46
47
Parameters:
48
- code (str): Code containing object to inspect
49
- cursor_pos (int): Cursor position in code
50
- detail_level (int): Level of detail (0 or 1)
51
52
Returns:
53
str: Message ID for tracking the request
54
"""
55
56
def history(self, raw=True, output=False, hist_access_type='range',
57
session=None, start=None, stop=None, n=None,
58
pattern=None, unique=False):
59
"""
60
Request execution history from kernel.
61
62
Parameters:
63
- raw (bool): Return raw input if True
64
- output (bool): Include output if True
65
- hist_access_type (str): 'range', 'tail', or 'search'
66
- session (int): Session number
67
- start (int): Start of range
68
- stop (int): End of range
69
- n (int): Number of entries for 'tail'
70
- pattern (str): Search pattern for 'search'
71
- unique (bool): Return unique entries only
72
73
Returns:
74
str: Message ID for tracking the request
75
"""
76
77
def kernel_info(self):
78
"""
79
Request kernel information.
80
81
Returns:
82
str: Message ID for tracking the request
83
"""
84
85
def comm_info(self, target_name=None):
86
"""
87
Request information about active comms.
88
89
Parameters:
90
- target_name (str): Specific comm target to query
91
92
Returns:
93
str: Message ID for tracking the request
94
"""
95
96
def is_complete(self, code):
97
"""
98
Check if code is complete and ready to execute.
99
100
Parameters:
101
- code (str): Code to check
102
103
Returns:
104
str: Message ID for tracking the request
105
"""
106
107
def shutdown(self, restart=False):
108
"""
109
Request kernel shutdown.
110
111
Parameters:
112
- restart (bool): Restart after shutdown if True
113
114
Returns:
115
str: Message ID for tracking the request
116
"""
117
118
def input(self, string):
119
"""
120
Send input to kernel in response to input_request.
121
122
Parameters:
123
- string (str): Input string to send
124
125
Returns:
126
None
127
"""
128
129
def start_channels(self, shell=True, iopub=True, stdin=True,
130
hb=True, control=True):
131
"""
132
Start the kernel communication channels.
133
134
Parameters:
135
- shell (bool): Start shell channel
136
- iopub (bool): Start iopub channel
137
- stdin (bool): Start stdin channel
138
- hb (bool): Start heartbeat channel
139
- control (bool): Start control channel
140
141
Returns:
142
None
143
"""
144
145
def stop_channels(self):
146
"""
147
Stop all communication channels.
148
149
Returns:
150
None
151
"""
152
153
@property
154
def channels_running(self):
155
"""Boolean indicating if channels are active."""
156
157
@property
158
def shell_channel(self):
159
"""Shell channel for execute requests."""
160
161
@property
162
def iopub_channel(self):
163
"""IOPub channel for kernel output."""
164
165
@property
166
def stdin_channel(self):
167
"""Stdin channel for input requests."""
168
169
@property
170
def hb_channel(self):
171
"""Heartbeat channel for kernel monitoring."""
172
173
@property
174
def control_channel(self):
175
"""Control channel for kernel management."""
176
```
177
178
### Blocking Kernel Client
179
180
The `BlockingKernelClient` provides synchronous message handling with blocking methods for receiving kernel responses.
181
182
```python { .api }
183
class BlockingKernelClient(KernelClient):
184
"""Synchronous kernel client with blocking message methods."""
185
186
def get_shell_msg(self, block=True, timeout=None):
187
"""
188
Get a message from the shell channel (blocking).
189
190
Parameters:
191
- block (bool): Block until message received
192
- timeout (float): Timeout in seconds
193
194
Returns:
195
dict: Jupyter protocol message
196
"""
197
198
def get_iopub_msg(self, block=True, timeout=None):
199
"""
200
Get a message from the iopub channel (blocking).
201
202
Parameters:
203
- block (bool): Block until message received
204
- timeout (float): Timeout in seconds
205
206
Returns:
207
dict: Jupyter protocol message
208
"""
209
210
def get_stdin_msg(self, block=True, timeout=None):
211
"""
212
Get a message from the stdin channel (blocking).
213
214
Parameters:
215
- block (bool): Block until message received
216
- timeout (float): Timeout in seconds
217
218
Returns:
219
dict: Jupyter protocol message
220
"""
221
222
def get_control_msg(self, block=True, timeout=None):
223
"""
224
Get a message from the control channel (blocking).
225
226
Parameters:
227
- block (bool): Block until message received
228
- timeout (float): Timeout in seconds
229
230
Returns:
231
dict: Jupyter protocol message
232
"""
233
234
def wait_for_ready(self, timeout=None):
235
"""
236
Wait for kernel to be ready for communication (blocking).
237
238
Parameters:
239
- timeout (float): Timeout in seconds
240
241
Returns:
242
None
243
"""
244
245
def is_alive(self):
246
"""
247
Check if kernel is alive (blocking).
248
249
Returns:
250
bool: True if kernel is responsive
251
"""
252
253
def execute_interactive(self, code, silent=False, store_history=True,
254
user_expressions=None, allow_stdin=None,
255
stop_on_error=True, timeout=None,
256
output_hook=None, stdin_hook=None):
257
"""
258
Execute code with interactive output handling (blocking).
259
260
Parameters:
261
- code (str): Code to execute
262
- silent (bool): Don't display output if True
263
- store_history (bool): Store in history if True
264
- user_expressions (dict): Expressions to evaluate
265
- allow_stdin (bool): Allow stdin requests
266
- stop_on_error (bool): Stop on first error
267
- timeout (float): Execution timeout
268
- output_hook (callable): Function to handle output
269
- stdin_hook (callable): Function to handle stdin requests
270
271
Returns:
272
dict: Execution reply message
273
"""
274
```
275
276
### Async Kernel Client
277
278
The `AsyncKernelClient` provides asynchronous message handling with async/await methods for non-blocking kernel communication.
279
280
```python { .api }
281
class AsyncKernelClient(KernelClient):
282
"""Asynchronous kernel client with async/await methods."""
283
284
async def get_shell_msg(self, timeout=None):
285
"""
286
Get a message from the shell channel (async).
287
288
Parameters:
289
- timeout (float): Timeout in seconds
290
291
Returns:
292
dict: Jupyter protocol message
293
"""
294
295
async def get_iopub_msg(self, timeout=None):
296
"""
297
Get a message from the iopub channel (async).
298
299
Parameters:
300
- timeout (float): Timeout in seconds
301
302
Returns:
303
dict: Jupyter protocol message
304
"""
305
306
async def get_stdin_msg(self, timeout=None):
307
"""
308
Get a message from the stdin channel (async).
309
310
Parameters:
311
- timeout (float): Timeout in seconds
312
313
Returns:
314
dict: Jupyter protocol message
315
"""
316
317
async def get_control_msg(self, timeout=None):
318
"""
319
Get a message from the control channel (async).
320
321
Parameters:
322
- timeout (float): Timeout in seconds
323
324
Returns:
325
dict: Jupyter protocol message
326
"""
327
328
async def wait_for_ready(self, timeout=None):
329
"""
330
Wait for kernel to be ready (async).
331
332
Parameters:
333
- timeout (float): Timeout in seconds
334
335
Returns:
336
None
337
"""
338
339
async def is_alive(self):
340
"""
341
Check if kernel is alive (async).
342
343
Returns:
344
bool: True if kernel is responsive
345
"""
346
347
async def execute_interactive(self, code, silent=False, store_history=True,
348
user_expressions=None, allow_stdin=None,
349
stop_on_error=True, timeout=None,
350
output_hook=None, stdin_hook=None):
351
"""
352
Execute code with interactive output handling (async).
353
354
Parameters:
355
- code (str): Code to execute
356
- silent (bool): Don't display output if True
357
- store_history (bool): Store in history if True
358
- user_expressions (dict): Expressions to evaluate
359
- allow_stdin (bool): Allow stdin requests
360
- stop_on_error (bool): Stop on first error
361
- timeout (float): Execution timeout
362
- output_hook (callable): Async function to handle output
363
- stdin_hook (callable): Async function to handle stdin
364
365
Returns:
366
dict: Execution reply message
367
"""
368
```
369
370
### Threaded Kernel Client
371
372
```python { .api }
373
class ThreadedKernelClient(KernelClient):
374
"""Kernel client using threaded ZMQ channels with IOLoop."""
375
```
376
377
## Usage Examples
378
379
### Basic Code Execution (Blocking)
380
381
```python
382
from jupyter_client import KernelManager
383
384
# Create and start kernel
385
km = KernelManager()
386
km.start_kernel()
387
388
# Create blocking client
389
kc = km.client()
390
kc.start_channels()
391
392
# Wait for kernel to be ready
393
kc.wait_for_ready()
394
395
# Execute code
396
msg_id = kc.execute("x = 1 + 1\nprint(x)")
397
398
# Get execution result
399
while True:
400
msg = kc.get_iopub_msg()
401
if msg['msg_type'] == 'execute_result':
402
print("Result:", msg['content']['data'])
403
break
404
elif msg['msg_type'] == 'stream':
405
print("Output:", msg['content']['text'])
406
elif msg['msg_type'] == 'status' and msg['content']['execution_state'] == 'idle':
407
break
408
409
# Clean up
410
kc.stop_channels()
411
km.shutdown_kernel()
412
```
413
414
### Interactive Execution (Blocking)
415
416
```python
417
from jupyter_client import KernelManager
418
419
km = KernelManager()
420
km.start_kernel()
421
kc = km.client()
422
kc.start_channels()
423
424
# Execute with output handling
425
def handle_output(msg):
426
if msg['msg_type'] == 'stream':
427
print(f"Stream: {msg['content']['text']}")
428
elif msg['msg_type'] == 'execute_result':
429
print(f"Result: {msg['content']['data']}")
430
431
reply = kc.execute_interactive("print('Hello, World!')", output_hook=handle_output)
432
print(f"Execution status: {reply['content']['status']}")
433
434
kc.stop_channels()
435
km.shutdown_kernel()
436
```
437
438
### Async Code Execution
439
440
```python
441
import asyncio
442
from jupyter_client import AsyncKernelManager
443
444
async def execute_async():
445
km = AsyncKernelManager()
446
await km.start_kernel()
447
448
kc = km.client()
449
await kc.start_channels()
450
await kc.wait_for_ready()
451
452
# Execute code
453
msg_id = kc.execute("import numpy as np\nresult = np.array([1, 2, 3]).sum()")
454
455
# Get results asynchronously
456
async def handle_output(msg):
457
if msg['msg_type'] == 'execute_result':
458
print(f"Result: {msg['content']['data']}")
459
460
reply = await kc.execute_interactive(
461
"print('Async execution')",
462
output_hook=handle_output
463
)
464
465
await kc.stop_channels()
466
await km.shutdown_kernel()
467
468
# Run async function
469
asyncio.run(execute_async())
470
```
471
472
### Code Completion and Inspection
473
474
```python
475
from jupyter_client import KernelManager
476
477
km = KernelManager()
478
km.start_kernel()
479
kc = km.client()
480
kc.start_channels()
481
kc.wait_for_ready()
482
483
# Request completion
484
msg_id = kc.complete("import num", cursor_pos=10)
485
reply = kc.get_shell_msg()
486
completions = reply['content']['matches']
487
print(f"Completions: {completions}")
488
489
# Request object inspection
490
msg_id = kc.inspect("len", cursor_pos=3)
491
reply = kc.get_shell_msg()
492
if reply['content']['found']:
493
print(f"Documentation: {reply['content']['data']['text/plain']}")
494
495
kc.stop_channels()
496
km.shutdown_kernel()
497
```