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
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
|
<span id="asyncio-transports-protocols"></span><h1>Transports and Protocols</h1> <h4 class="rubric">Preface</h4> <p>Transports and Protocols are used by the <strong>low-level</strong> event loop APIs such as <a class="reference internal" href="asyncio-eventloop#asyncio.loop.create_connection" title="asyncio.loop.create_connection"><code>loop.create_connection()</code></a>. They use callback-based programming style and enable high-performance implementations of network or IPC protocols (e.g. HTTP).</p> <p>Essentially, transports and protocols should only be used in libraries and frameworks and never in high-level asyncio applications.</p> <p>This documentation page covers both <a class="reference internal" href="#transports">Transports</a> and <a class="reference internal" href="#protocols">Protocols</a>.</p> <h4 class="rubric">Introduction</h4> <p>At the highest level, the transport is concerned with <em>how</em> bytes are transmitted, while the protocol determines <em>which</em> bytes to transmit (and to some extent when).</p> <p>A different way of saying the same thing: a transport is an abstraction for a socket (or similar I/O endpoint) while a protocol is an abstraction for an application, from the transport’s point of view.</p> <p>Yet another view is the transport and protocol interfaces together define an abstract interface for using network I/O and interprocess I/O.</p> <p>There is always a 1:1 relationship between transport and protocol objects: the protocol calls transport methods to send data, while the transport calls protocol methods to pass it data that has been received.</p> <p>Most of connection oriented event loop methods (such as <a class="reference internal" href="asyncio-eventloop#asyncio.loop.create_connection" title="asyncio.loop.create_connection"><code>loop.create_connection()</code></a>) usually accept a <em>protocol_factory</em> argument used to create a <em>Protocol</em> object for an accepted connection, represented by a <em>Transport</em> object. Such methods usually return a tuple of <code>(transport, protocol)</code>.</p> <h4 class="rubric">Contents</h4> <p>This documentation page contains the following sections:</p> <ul class="simple"> <li>The <a class="reference internal" href="#transports">Transports</a> section documents asyncio <a class="reference internal" href="#asyncio.BaseTransport" title="asyncio.BaseTransport"><code>BaseTransport</code></a>, <a class="reference internal" href="#asyncio.ReadTransport" title="asyncio.ReadTransport"><code>ReadTransport</code></a>, <a class="reference internal" href="#asyncio.WriteTransport" title="asyncio.WriteTransport"><code>WriteTransport</code></a>, <a class="reference internal" href="#asyncio.Transport" title="asyncio.Transport"><code>Transport</code></a>, <a class="reference internal" href="#asyncio.DatagramTransport" title="asyncio.DatagramTransport"><code>DatagramTransport</code></a>, and <a class="reference internal" href="#asyncio.SubprocessTransport" title="asyncio.SubprocessTransport"><code>SubprocessTransport</code></a> classes.</li> <li>The <a class="reference internal" href="#protocols">Protocols</a> section documents asyncio <a class="reference internal" href="#asyncio.BaseProtocol" title="asyncio.BaseProtocol"><code>BaseProtocol</code></a>, <a class="reference internal" href="#asyncio.Protocol" title="asyncio.Protocol"><code>Protocol</code></a>, <a class="reference internal" href="#asyncio.BufferedProtocol" title="asyncio.BufferedProtocol"><code>BufferedProtocol</code></a>, <a class="reference internal" href="#asyncio.DatagramProtocol" title="asyncio.DatagramProtocol"><code>DatagramProtocol</code></a>, and <a class="reference internal" href="#asyncio.SubprocessProtocol" title="asyncio.SubprocessProtocol"><code>SubprocessProtocol</code></a> classes.</li> <li>The <a class="reference internal" href="#examples">Examples</a> section showcases how to work with transports, protocols, and low-level event loop APIs.</li> </ul> <section id="transports"> <span id="asyncio-transport"></span><h2>Transports</h2> <p><strong>Source code:</strong> <a class="reference external" href="https://github.com/python/cpython/tree/3.12/Lib/asyncio/transports.py">Lib/asyncio/transports.py</a></p> <p>Transports are classes provided by <a class="reference internal" href="asyncio#module-asyncio" title="asyncio: Asynchronous I/O."><code>asyncio</code></a> in order to abstract various kinds of communication channels.</p> <p>Transport objects are always instantiated by an <a class="reference internal" href="asyncio-eventloop#asyncio-event-loop"><span class="std std-ref">asyncio event loop</span></a>.</p> <p>asyncio implements transports for TCP, UDP, SSL, and subprocess pipes. The methods available on a transport depend on the transport’s kind.</p> <p>The transport classes are <a class="reference internal" href="asyncio-dev#asyncio-multithreading"><span class="std std-ref">not thread safe</span></a>.</p> <section id="transports-hierarchy"> <h3>Transports Hierarchy</h3> <dl class="py class"> <dt class="sig sig-object py" id="asyncio.BaseTransport">
<code>class asyncio.BaseTransport</code> </dt> <dd>
<p>Base class for all transports. Contains methods that all asyncio transports share.</p> </dd>
</dl> <dl class="py class"> <dt class="sig sig-object py" id="asyncio.WriteTransport">
<code>class asyncio.WriteTransport(BaseTransport)</code> </dt> <dd>
<p>A base transport for write-only connections.</p> <p>Instances of the <em>WriteTransport</em> class are returned from the <a class="reference internal" href="asyncio-eventloop#asyncio.loop.connect_write_pipe" title="asyncio.loop.connect_write_pipe"><code>loop.connect_write_pipe()</code></a> event loop method and are also used by subprocess-related methods like <a class="reference internal" href="asyncio-eventloop#asyncio.loop.subprocess_exec" title="asyncio.loop.subprocess_exec"><code>loop.subprocess_exec()</code></a>.</p> </dd>
</dl> <dl class="py class"> <dt class="sig sig-object py" id="asyncio.ReadTransport">
<code>class asyncio.ReadTransport(BaseTransport)</code> </dt> <dd>
<p>A base transport for read-only connections.</p> <p>Instances of the <em>ReadTransport</em> class are returned from the <a class="reference internal" href="asyncio-eventloop#asyncio.loop.connect_read_pipe" title="asyncio.loop.connect_read_pipe"><code>loop.connect_read_pipe()</code></a> event loop method and are also used by subprocess-related methods like <a class="reference internal" href="asyncio-eventloop#asyncio.loop.subprocess_exec" title="asyncio.loop.subprocess_exec"><code>loop.subprocess_exec()</code></a>.</p> </dd>
</dl> <dl class="py class"> <dt class="sig sig-object py" id="asyncio.Transport">
<code>class asyncio.Transport(WriteTransport, ReadTransport)</code> </dt> <dd>
<p>Interface representing a bidirectional transport, such as a TCP connection.</p> <p>The user does not instantiate a transport directly; they call a utility function, passing it a protocol factory and other information necessary to create the transport and protocol.</p> <p>Instances of the <em>Transport</em> class are returned from or used by event loop methods like <a class="reference internal" href="asyncio-eventloop#asyncio.loop.create_connection" title="asyncio.loop.create_connection"><code>loop.create_connection()</code></a>, <a class="reference internal" href="asyncio-eventloop#asyncio.loop.create_unix_connection" title="asyncio.loop.create_unix_connection"><code>loop.create_unix_connection()</code></a>, <a class="reference internal" href="asyncio-eventloop#asyncio.loop.create_server" title="asyncio.loop.create_server"><code>loop.create_server()</code></a>, <a class="reference internal" href="asyncio-eventloop#asyncio.loop.sendfile" title="asyncio.loop.sendfile"><code>loop.sendfile()</code></a>, etc.</p> </dd>
</dl> <dl class="py class"> <dt class="sig sig-object py" id="asyncio.DatagramTransport">
<code>class asyncio.DatagramTransport(BaseTransport)</code> </dt> <dd>
<p>A transport for datagram (UDP) connections.</p> <p>Instances of the <em>DatagramTransport</em> class are returned from the <a class="reference internal" href="asyncio-eventloop#asyncio.loop.create_datagram_endpoint" title="asyncio.loop.create_datagram_endpoint"><code>loop.create_datagram_endpoint()</code></a> event loop method.</p> </dd>
</dl> <dl class="py class"> <dt class="sig sig-object py" id="asyncio.SubprocessTransport">
<code>class asyncio.SubprocessTransport(BaseTransport)</code> </dt> <dd>
<p>An abstraction to represent a connection between a parent and its child OS process.</p> <p>Instances of the <em>SubprocessTransport</em> class are returned from event loop methods <a class="reference internal" href="asyncio-eventloop#asyncio.loop.subprocess_shell" title="asyncio.loop.subprocess_shell"><code>loop.subprocess_shell()</code></a> and <a class="reference internal" href="asyncio-eventloop#asyncio.loop.subprocess_exec" title="asyncio.loop.subprocess_exec"><code>loop.subprocess_exec()</code></a>.</p> </dd>
</dl> </section> <section id="base-transport"> <h3>Base Transport</h3> <dl class="py method"> <dt class="sig sig-object py" id="asyncio.BaseTransport.close">
<code>BaseTransport.close()</code> </dt> <dd>
<p>Close the transport.</p> <p>If the transport has a buffer for outgoing data, buffered data will be flushed asynchronously. No more data will be received. After all buffered data is flushed, the protocol’s <a class="reference internal" href="#asyncio.BaseProtocol.connection_lost" title="asyncio.BaseProtocol.connection_lost"><code>protocol.connection_lost()</code></a> method will be called with <a class="reference internal" href="constants#None" title="None"><code>None</code></a> as its argument. The transport should not be used once it is closed.</p> </dd>
</dl> <dl class="py method"> <dt class="sig sig-object py" id="asyncio.BaseTransport.is_closing">
<code>BaseTransport.is_closing()</code> </dt> <dd>
<p>Return <code>True</code> if the transport is closing or is closed.</p> </dd>
</dl> <dl class="py method"> <dt class="sig sig-object py" id="asyncio.BaseTransport.get_extra_info">
<code>BaseTransport.get_extra_info(name, default=None)</code> </dt> <dd>
<p>Return information about the transport or underlying resources it uses.</p> <p><em>name</em> is a string representing the piece of transport-specific information to get.</p> <p><em>default</em> is the value to return if the information is not available, or if the transport does not support querying it with the given third-party event loop implementation or on the current platform.</p> <p>For example, the following code attempts to get the underlying socket object of the transport:</p> <pre data-language="python">sock = transport.get_extra_info('socket')
if sock is not None:
print(sock.getsockopt(...))
</pre> <p>Categories of information that can be queried on some transports:</p> <ul class="simple"> <li>
<p>socket:</p> <ul> <li>
<code>'peername'</code>: the remote address to which the socket is connected, result of <a class="reference internal" href="socket#socket.socket.getpeername" title="socket.socket.getpeername"><code>socket.socket.getpeername()</code></a> (<code>None</code> on error)</li> <li>
<code>'socket'</code>: <a class="reference internal" href="socket#socket.socket" title="socket.socket"><code>socket.socket</code></a> instance</li> <li>
<code>'sockname'</code>: the socket’s own address, result of <a class="reference internal" href="socket#socket.socket.getsockname" title="socket.socket.getsockname"><code>socket.socket.getsockname()</code></a>
</li> </ul> </li> <li>
<p>SSL socket:</p> <ul> <li>
<code>'compression'</code>: the compression algorithm being used as a string, or <code>None</code> if the connection isn’t compressed; result of <a class="reference internal" href="ssl#ssl.SSLSocket.compression" title="ssl.SSLSocket.compression"><code>ssl.SSLSocket.compression()</code></a>
</li> <li>
<code>'cipher'</code>: a three-value tuple containing the name of the cipher being used, the version of the SSL protocol that defines its use, and the number of secret bits being used; result of <a class="reference internal" href="ssl#ssl.SSLSocket.cipher" title="ssl.SSLSocket.cipher"><code>ssl.SSLSocket.cipher()</code></a>
</li> <li>
<code>'peercert'</code>: peer certificate; result of <a class="reference internal" href="ssl#ssl.SSLSocket.getpeercert" title="ssl.SSLSocket.getpeercert"><code>ssl.SSLSocket.getpeercert()</code></a>
</li> <li>
<code>'sslcontext'</code>: <a class="reference internal" href="ssl#ssl.SSLContext" title="ssl.SSLContext"><code>ssl.SSLContext</code></a> instance</li> <li>
<code>'ssl_object'</code>: <a class="reference internal" href="ssl#ssl.SSLObject" title="ssl.SSLObject"><code>ssl.SSLObject</code></a> or <a class="reference internal" href="ssl#ssl.SSLSocket" title="ssl.SSLSocket"><code>ssl.SSLSocket</code></a> instance</li> </ul> </li> <li>
<p>pipe:</p> <ul> <li>
<code>'pipe'</code>: pipe object</li> </ul> </li> <li>
<p>subprocess:</p> <ul> <li>
<code>'subprocess'</code>: <a class="reference internal" href="subprocess#subprocess.Popen" title="subprocess.Popen"><code>subprocess.Popen</code></a> instance</li> </ul> </li> </ul> </dd>
</dl> <dl class="py method"> <dt class="sig sig-object py" id="asyncio.BaseTransport.set_protocol">
<code>BaseTransport.set_protocol(protocol)</code> </dt> <dd>
<p>Set a new protocol.</p> <p>Switching protocol should only be done when both protocols are documented to support the switch.</p> </dd>
</dl> <dl class="py method"> <dt class="sig sig-object py" id="asyncio.BaseTransport.get_protocol">
<code>BaseTransport.get_protocol()</code> </dt> <dd>
<p>Return the current protocol.</p> </dd>
</dl> </section> <section id="read-only-transports"> <h3>Read-only Transports</h3> <dl class="py method"> <dt class="sig sig-object py" id="asyncio.ReadTransport.is_reading">
<code>ReadTransport.is_reading()</code> </dt> <dd>
<p>Return <code>True</code> if the transport is receiving new data.</p> <div class="versionadded"> <p><span class="versionmodified added">New in version 3.7.</span></p> </div> </dd>
</dl> <dl class="py method"> <dt class="sig sig-object py" id="asyncio.ReadTransport.pause_reading">
<code>ReadTransport.pause_reading()</code> </dt> <dd>
<p>Pause the receiving end of the transport. No data will be passed to the protocol’s <a class="reference internal" href="#asyncio.Protocol.data_received" title="asyncio.Protocol.data_received"><code>protocol.data_received()</code></a> method until <a class="reference internal" href="#asyncio.ReadTransport.resume_reading" title="asyncio.ReadTransport.resume_reading"><code>resume_reading()</code></a> is called.</p> <div class="versionchanged"> <p><span class="versionmodified changed">Changed in version 3.7: </span>The method is idempotent, i.e. it can be called when the transport is already paused or closed.</p> </div> </dd>
</dl> <dl class="py method"> <dt class="sig sig-object py" id="asyncio.ReadTransport.resume_reading">
<code>ReadTransport.resume_reading()</code> </dt> <dd>
<p>Resume the receiving end. The protocol’s <a class="reference internal" href="#asyncio.Protocol.data_received" title="asyncio.Protocol.data_received"><code>protocol.data_received()</code></a> method will be called once again if some data is available for reading.</p> <div class="versionchanged"> <p><span class="versionmodified changed">Changed in version 3.7: </span>The method is idempotent, i.e. it can be called when the transport is already reading.</p> </div> </dd>
</dl> </section> <section id="write-only-transports"> <h3>Write-only Transports</h3> <dl class="py method"> <dt class="sig sig-object py" id="asyncio.WriteTransport.abort">
<code>WriteTransport.abort()</code> </dt> <dd>
<p>Close the transport immediately, without waiting for pending operations to complete. Buffered data will be lost. No more data will be received. The protocol’s <a class="reference internal" href="#asyncio.BaseProtocol.connection_lost" title="asyncio.BaseProtocol.connection_lost"><code>protocol.connection_lost()</code></a> method will eventually be called with <a class="reference internal" href="constants#None" title="None"><code>None</code></a> as its argument.</p> </dd>
</dl> <dl class="py method"> <dt class="sig sig-object py" id="asyncio.WriteTransport.can_write_eof">
<code>WriteTransport.can_write_eof()</code> </dt> <dd>
<p>Return <a class="reference internal" href="constants#True" title="True"><code>True</code></a> if the transport supports <a class="reference internal" href="#asyncio.WriteTransport.write_eof" title="asyncio.WriteTransport.write_eof"><code>write_eof()</code></a>, <a class="reference internal" href="constants#False" title="False"><code>False</code></a> if not.</p> </dd>
</dl> <dl class="py method"> <dt class="sig sig-object py" id="asyncio.WriteTransport.get_write_buffer_size">
<code>WriteTransport.get_write_buffer_size()</code> </dt> <dd>
<p>Return the current size of the output buffer used by the transport.</p> </dd>
</dl> <dl class="py method"> <dt class="sig sig-object py" id="asyncio.WriteTransport.get_write_buffer_limits">
<code>WriteTransport.get_write_buffer_limits()</code> </dt> <dd>
<p>Get the <em>high</em> and <em>low</em> watermarks for write flow control. Return a tuple <code>(low, high)</code> where <em>low</em> and <em>high</em> are positive number of bytes.</p> <p>Use <a class="reference internal" href="#asyncio.WriteTransport.set_write_buffer_limits" title="asyncio.WriteTransport.set_write_buffer_limits"><code>set_write_buffer_limits()</code></a> to set the limits.</p> <div class="versionadded"> <p><span class="versionmodified added">New in version 3.4.2.</span></p> </div> </dd>
</dl> <dl class="py method"> <dt class="sig sig-object py" id="asyncio.WriteTransport.set_write_buffer_limits">
<code>WriteTransport.set_write_buffer_limits(high=None, low=None)</code> </dt> <dd>
<p>Set the <em>high</em> and <em>low</em> watermarks for write flow control.</p> <p>These two values (measured in number of bytes) control when the protocol’s <a class="reference internal" href="#asyncio.BaseProtocol.pause_writing" title="asyncio.BaseProtocol.pause_writing"><code>protocol.pause_writing()</code></a> and <a class="reference internal" href="#asyncio.BaseProtocol.resume_writing" title="asyncio.BaseProtocol.resume_writing"><code>protocol.resume_writing()</code></a> methods are called. If specified, the low watermark must be less than or equal to the high watermark. Neither <em>high</em> nor <em>low</em> can be negative.</p> <p><a class="reference internal" href="#asyncio.BaseProtocol.pause_writing" title="asyncio.BaseProtocol.pause_writing"><code>pause_writing()</code></a> is called when the buffer size becomes greater than or equal to the <em>high</em> value. If writing has been paused, <a class="reference internal" href="#asyncio.BaseProtocol.resume_writing" title="asyncio.BaseProtocol.resume_writing"><code>resume_writing()</code></a> is called when the buffer size becomes less than or equal to the <em>low</em> value.</p> <p>The defaults are implementation-specific. If only the high watermark is given, the low watermark defaults to an implementation-specific value less than or equal to the high watermark. Setting <em>high</em> to zero forces <em>low</em> to zero as well, and causes <a class="reference internal" href="#asyncio.BaseProtocol.pause_writing" title="asyncio.BaseProtocol.pause_writing"><code>pause_writing()</code></a> to be called whenever the buffer becomes non-empty. Setting <em>low</em> to zero causes <a class="reference internal" href="#asyncio.BaseProtocol.resume_writing" title="asyncio.BaseProtocol.resume_writing"><code>resume_writing()</code></a> to be called only once the buffer is empty. Use of zero for either limit is generally sub-optimal as it reduces opportunities for doing I/O and computation concurrently.</p> <p>Use <a class="reference internal" href="#asyncio.WriteTransport.get_write_buffer_limits" title="asyncio.WriteTransport.get_write_buffer_limits"><code>get_write_buffer_limits()</code></a> to get the limits.</p> </dd>
</dl> <dl class="py method"> <dt class="sig sig-object py" id="asyncio.WriteTransport.write">
<code>WriteTransport.write(data)</code> </dt> <dd>
<p>Write some <em>data</em> bytes to the transport.</p> <p>This method does not block; it buffers the data and arranges for it to be sent out asynchronously.</p> </dd>
</dl> <dl class="py method"> <dt class="sig sig-object py" id="asyncio.WriteTransport.writelines">
<code>WriteTransport.writelines(list_of_data)</code> </dt> <dd>
<p>Write a list (or any iterable) of data bytes to the transport. This is functionally equivalent to calling <a class="reference internal" href="#asyncio.WriteTransport.write" title="asyncio.WriteTransport.write"><code>write()</code></a> on each element yielded by the iterable, but may be implemented more efficiently.</p> </dd>
</dl> <dl class="py method"> <dt class="sig sig-object py" id="asyncio.WriteTransport.write_eof">
<code>WriteTransport.write_eof()</code> </dt> <dd>
<p>Close the write end of the transport after flushing all buffered data. Data may still be received.</p> <p>This method can raise <a class="reference internal" href="exceptions#NotImplementedError" title="NotImplementedError"><code>NotImplementedError</code></a> if the transport (e.g. SSL) doesn’t support half-closed connections.</p> </dd>
</dl> </section> <section id="datagram-transports"> <h3>Datagram Transports</h3> <dl class="py method"> <dt class="sig sig-object py" id="asyncio.DatagramTransport.sendto">
<code>DatagramTransport.sendto(data, addr=None)</code> </dt> <dd>
<p>Send the <em>data</em> bytes to the remote peer given by <em>addr</em> (a transport-dependent target address). If <em>addr</em> is <a class="reference internal" href="constants#None" title="None"><code>None</code></a>, the data is sent to the target address given on transport creation.</p> <p>This method does not block; it buffers the data and arranges for it to be sent out asynchronously.</p> </dd>
</dl> <dl class="py method"> <dt class="sig sig-object py" id="asyncio.DatagramTransport.abort">
<code>DatagramTransport.abort()</code> </dt> <dd>
<p>Close the transport immediately, without waiting for pending operations to complete. Buffered data will be lost. No more data will be received. The protocol’s <a class="reference internal" href="#asyncio.BaseProtocol.connection_lost" title="asyncio.BaseProtocol.connection_lost"><code>protocol.connection_lost()</code></a> method will eventually be called with <a class="reference internal" href="constants#None" title="None"><code>None</code></a> as its argument.</p> </dd>
</dl> </section> <section id="subprocess-transports"> <span id="asyncio-subprocess-transports"></span><h3>Subprocess Transports</h3> <dl class="py method"> <dt class="sig sig-object py" id="asyncio.SubprocessTransport.get_pid">
<code>SubprocessTransport.get_pid()</code> </dt> <dd>
<p>Return the subprocess process id as an integer.</p> </dd>
</dl> <dl class="py method"> <dt class="sig sig-object py" id="asyncio.SubprocessTransport.get_pipe_transport">
<code>SubprocessTransport.get_pipe_transport(fd)</code> </dt> <dd>
<p>Return the transport for the communication pipe corresponding to the integer file descriptor <em>fd</em>:</p> <ul class="simple"> <li>
<code>0</code>: readable streaming transport of the standard input (<em>stdin</em>), or <a class="reference internal" href="constants#None" title="None"><code>None</code></a> if the subprocess was not created with <code>stdin=PIPE</code>
</li> <li>
<code>1</code>: writable streaming transport of the standard output (<em>stdout</em>), or <a class="reference internal" href="constants#None" title="None"><code>None</code></a> if the subprocess was not created with <code>stdout=PIPE</code>
</li> <li>
<code>2</code>: writable streaming transport of the standard error (<em>stderr</em>), or <a class="reference internal" href="constants#None" title="None"><code>None</code></a> if the subprocess was not created with <code>stderr=PIPE</code>
</li> <li>other <em>fd</em>: <a class="reference internal" href="constants#None" title="None"><code>None</code></a>
</li> </ul> </dd>
</dl> <dl class="py method"> <dt class="sig sig-object py" id="asyncio.SubprocessTransport.get_returncode">
<code>SubprocessTransport.get_returncode()</code> </dt> <dd>
<p>Return the subprocess return code as an integer or <a class="reference internal" href="constants#None" title="None"><code>None</code></a> if it hasn’t returned, which is similar to the <a class="reference internal" href="subprocess#subprocess.Popen.returncode" title="subprocess.Popen.returncode"><code>subprocess.Popen.returncode</code></a> attribute.</p> </dd>
</dl> <dl class="py method"> <dt class="sig sig-object py" id="asyncio.SubprocessTransport.kill">
<code>SubprocessTransport.kill()</code> </dt> <dd>
<p>Kill the subprocess.</p> <p>On POSIX systems, the function sends SIGKILL to the subprocess. On Windows, this method is an alias for <a class="reference internal" href="#asyncio.SubprocessTransport.terminate" title="asyncio.SubprocessTransport.terminate"><code>terminate()</code></a>.</p> <p>See also <a class="reference internal" href="subprocess#subprocess.Popen.kill" title="subprocess.Popen.kill"><code>subprocess.Popen.kill()</code></a>.</p> </dd>
</dl> <dl class="py method"> <dt class="sig sig-object py" id="asyncio.SubprocessTransport.send_signal">
<code>SubprocessTransport.send_signal(signal)</code> </dt> <dd>
<p>Send the <em>signal</em> number to the subprocess, as in <a class="reference internal" href="subprocess#subprocess.Popen.send_signal" title="subprocess.Popen.send_signal"><code>subprocess.Popen.send_signal()</code></a>.</p> </dd>
</dl> <dl class="py method"> <dt class="sig sig-object py" id="asyncio.SubprocessTransport.terminate">
<code>SubprocessTransport.terminate()</code> </dt> <dd>
<p>Stop the subprocess.</p> <p>On POSIX systems, this method sends SIGTERM to the subprocess. On Windows, the Windows API function TerminateProcess() is called to stop the subprocess.</p> <p>See also <a class="reference internal" href="subprocess#subprocess.Popen.terminate" title="subprocess.Popen.terminate"><code>subprocess.Popen.terminate()</code></a>.</p> </dd>
</dl> <dl class="py method"> <dt class="sig sig-object py" id="asyncio.SubprocessTransport.close">
<code>SubprocessTransport.close()</code> </dt> <dd>
<p>Kill the subprocess by calling the <a class="reference internal" href="#asyncio.SubprocessTransport.kill" title="asyncio.SubprocessTransport.kill"><code>kill()</code></a> method.</p> <p>If the subprocess hasn’t returned yet, and close transports of <em>stdin</em>, <em>stdout</em>, and <em>stderr</em> pipes.</p> </dd>
</dl> </section> </section> <section id="protocols"> <span id="asyncio-protocol"></span><h2>Protocols</h2> <p><strong>Source code:</strong> <a class="reference external" href="https://github.com/python/cpython/tree/3.12/Lib/asyncio/protocols.py">Lib/asyncio/protocols.py</a></p> <p>asyncio provides a set of abstract base classes that should be used to implement network protocols. Those classes are meant to be used together with <a class="reference internal" href="#asyncio-transport"><span class="std std-ref">transports</span></a>.</p> <p>Subclasses of abstract base protocol classes may implement some or all methods. All these methods are callbacks: they are called by transports on certain events, for example when some data is received. A base protocol method should be called by the corresponding transport.</p> <section id="base-protocols"> <h3>Base Protocols</h3> <dl class="py class"> <dt class="sig sig-object py" id="asyncio.BaseProtocol">
<code>class asyncio.BaseProtocol</code> </dt> <dd>
<p>Base protocol with methods that all protocols share.</p> </dd>
</dl> <dl class="py class"> <dt class="sig sig-object py" id="asyncio.Protocol">
<code>class asyncio.Protocol(BaseProtocol)</code> </dt> <dd>
<p>The base class for implementing streaming protocols (TCP, Unix sockets, etc).</p> </dd>
</dl> <dl class="py class"> <dt class="sig sig-object py" id="asyncio.BufferedProtocol">
<code>class asyncio.BufferedProtocol(BaseProtocol)</code> </dt> <dd>
<p>A base class for implementing streaming protocols with manual control of the receive buffer.</p> </dd>
</dl> <dl class="py class"> <dt class="sig sig-object py" id="asyncio.DatagramProtocol">
<code>class asyncio.DatagramProtocol(BaseProtocol)</code> </dt> <dd>
<p>The base class for implementing datagram (UDP) protocols.</p> </dd>
</dl> <dl class="py class"> <dt class="sig sig-object py" id="asyncio.SubprocessProtocol">
<code>class asyncio.SubprocessProtocol(BaseProtocol)</code> </dt> <dd>
<p>The base class for implementing protocols communicating with child processes (unidirectional pipes).</p> </dd>
</dl> </section> <section id="base-protocol"> <h3>Base Protocol</h3> <p>All asyncio protocols can implement Base Protocol callbacks.</p> <h4 class="rubric">Connection Callbacks</h4> <p>Connection callbacks are called on all protocols, exactly once per a successful connection. All other protocol callbacks can only be called between those two methods.</p> <dl class="py method"> <dt class="sig sig-object py" id="asyncio.BaseProtocol.connection_made">
<code>BaseProtocol.connection_made(transport)</code> </dt> <dd>
<p>Called when a connection is made.</p> <p>The <em>transport</em> argument is the transport representing the connection. The protocol is responsible for storing the reference to its transport.</p> </dd>
</dl> <dl class="py method"> <dt class="sig sig-object py" id="asyncio.BaseProtocol.connection_lost">
<code>BaseProtocol.connection_lost(exc)</code> </dt> <dd>
<p>Called when the connection is lost or closed.</p> <p>The argument is either an exception object or <a class="reference internal" href="constants#None" title="None"><code>None</code></a>. The latter means a regular EOF is received, or the connection was aborted or closed by this side of the connection.</p> </dd>
</dl> <h4 class="rubric">Flow Control Callbacks</h4> <p>Flow control callbacks can be called by transports to pause or resume writing performed by the protocol.</p> <p>See the documentation of the <a class="reference internal" href="#asyncio.WriteTransport.set_write_buffer_limits" title="asyncio.WriteTransport.set_write_buffer_limits"><code>set_write_buffer_limits()</code></a> method for more details.</p> <dl class="py method"> <dt class="sig sig-object py" id="asyncio.BaseProtocol.pause_writing">
<code>BaseProtocol.pause_writing()</code> </dt> <dd>
<p>Called when the transport’s buffer goes over the high watermark.</p> </dd>
</dl> <dl class="py method"> <dt class="sig sig-object py" id="asyncio.BaseProtocol.resume_writing">
<code>BaseProtocol.resume_writing()</code> </dt> <dd>
<p>Called when the transport’s buffer drains below the low watermark.</p> </dd>
</dl> <p>If the buffer size equals the high watermark, <a class="reference internal" href="#asyncio.BaseProtocol.pause_writing" title="asyncio.BaseProtocol.pause_writing"><code>pause_writing()</code></a> is not called: the buffer size must go strictly over.</p> <p>Conversely, <a class="reference internal" href="#asyncio.BaseProtocol.resume_writing" title="asyncio.BaseProtocol.resume_writing"><code>resume_writing()</code></a> is called when the buffer size is equal or lower than the low watermark. These end conditions are important to ensure that things go as expected when either mark is zero.</p> </section> <section id="streaming-protocols"> <h3>Streaming Protocols</h3> <p>Event methods, such as <a class="reference internal" href="asyncio-eventloop#asyncio.loop.create_server" title="asyncio.loop.create_server"><code>loop.create_server()</code></a>, <a class="reference internal" href="asyncio-eventloop#asyncio.loop.create_unix_server" title="asyncio.loop.create_unix_server"><code>loop.create_unix_server()</code></a>, <a class="reference internal" href="asyncio-eventloop#asyncio.loop.create_connection" title="asyncio.loop.create_connection"><code>loop.create_connection()</code></a>, <a class="reference internal" href="asyncio-eventloop#asyncio.loop.create_unix_connection" title="asyncio.loop.create_unix_connection"><code>loop.create_unix_connection()</code></a>, <a class="reference internal" href="asyncio-eventloop#asyncio.loop.connect_accepted_socket" title="asyncio.loop.connect_accepted_socket"><code>loop.connect_accepted_socket()</code></a>, <a class="reference internal" href="asyncio-eventloop#asyncio.loop.connect_read_pipe" title="asyncio.loop.connect_read_pipe"><code>loop.connect_read_pipe()</code></a>, and <a class="reference internal" href="asyncio-eventloop#asyncio.loop.connect_write_pipe" title="asyncio.loop.connect_write_pipe"><code>loop.connect_write_pipe()</code></a> accept factories that return streaming protocols.</p> <dl class="py method"> <dt class="sig sig-object py" id="asyncio.Protocol.data_received">
<code>Protocol.data_received(data)</code> </dt> <dd>
<p>Called when some data is received. <em>data</em> is a non-empty bytes object containing the incoming data.</p> <p>Whether the data is buffered, chunked or reassembled depends on the transport. In general, you shouldn’t rely on specific semantics and instead make your parsing generic and flexible. However, data is always received in the correct order.</p> <p>The method can be called an arbitrary number of times while a connection is open.</p> <p>However, <a class="reference internal" href="#asyncio.Protocol.eof_received" title="asyncio.Protocol.eof_received"><code>protocol.eof_received()</code></a> is called at most once. Once <code>eof_received()</code> is called, <code>data_received()</code> is not called anymore.</p> </dd>
</dl> <dl class="py method"> <dt class="sig sig-object py" id="asyncio.Protocol.eof_received">
<code>Protocol.eof_received()</code> </dt> <dd>
<p>Called when the other end signals it won’t send any more data (for example by calling <a class="reference internal" href="#asyncio.WriteTransport.write_eof" title="asyncio.WriteTransport.write_eof"><code>transport.write_eof()</code></a>, if the other end also uses asyncio).</p> <p>This method may return a false value (including <code>None</code>), in which case the transport will close itself. Conversely, if this method returns a true value, the protocol used determines whether to close the transport. Since the default implementation returns <code>None</code>, it implicitly closes the connection.</p> <p>Some transports, including SSL, don’t support half-closed connections, in which case returning true from this method will result in the connection being closed.</p> </dd>
</dl> <p>State machine:</p> <pre data-language="none">start -> connection_made
[-> data_received]*
[-> eof_received]?
-> connection_lost -> end
</pre> </section> <section id="buffered-streaming-protocols"> <h3>Buffered Streaming Protocols</h3> <div class="versionadded"> <p><span class="versionmodified added">New in version 3.7.</span></p> </div> <p>Buffered Protocols can be used with any event loop method that supports <a class="reference internal" href="#streaming-protocols">Streaming Protocols</a>.</p> <p><code>BufferedProtocol</code> implementations allow explicit manual allocation and control of the receive buffer. Event loops can then use the buffer provided by the protocol to avoid unnecessary data copies. This can result in noticeable performance improvement for protocols that receive big amounts of data. Sophisticated protocol implementations can significantly reduce the number of buffer allocations.</p> <p>The following callbacks are called on <a class="reference internal" href="#asyncio.BufferedProtocol" title="asyncio.BufferedProtocol"><code>BufferedProtocol</code></a> instances:</p> <dl class="py method"> <dt class="sig sig-object py" id="asyncio.BufferedProtocol.get_buffer">
<code>BufferedProtocol.get_buffer(sizehint)</code> </dt> <dd>
<p>Called to allocate a new receive buffer.</p> <p><em>sizehint</em> is the recommended minimum size for the returned buffer. It is acceptable to return smaller or larger buffers than what <em>sizehint</em> suggests. When set to -1, the buffer size can be arbitrary. It is an error to return a buffer with a zero size.</p> <p><code>get_buffer()</code> must return an object implementing the <a class="reference internal" href="../c-api/buffer#bufferobjects"><span class="std std-ref">buffer protocol</span></a>.</p> </dd>
</dl> <dl class="py method"> <dt class="sig sig-object py" id="asyncio.BufferedProtocol.buffer_updated">
<code>BufferedProtocol.buffer_updated(nbytes)</code> </dt> <dd>
<p>Called when the buffer was updated with the received data.</p> <p><em>nbytes</em> is the total number of bytes that were written to the buffer.</p> </dd>
</dl> <dl class="py method"> <dt class="sig sig-object py" id="asyncio.BufferedProtocol.eof_received">
<code>BufferedProtocol.eof_received()</code> </dt> <dd>
<p>See the documentation of the <a class="reference internal" href="#asyncio.Protocol.eof_received" title="asyncio.Protocol.eof_received"><code>protocol.eof_received()</code></a> method.</p> </dd>
</dl> <p><a class="reference internal" href="#asyncio.BufferedProtocol.get_buffer" title="asyncio.BufferedProtocol.get_buffer"><code>get_buffer()</code></a> can be called an arbitrary number of times during a connection. However, <a class="reference internal" href="#asyncio.Protocol.eof_received" title="asyncio.Protocol.eof_received"><code>protocol.eof_received()</code></a> is called at most once and, if called, <a class="reference internal" href="#asyncio.BufferedProtocol.get_buffer" title="asyncio.BufferedProtocol.get_buffer"><code>get_buffer()</code></a> and <a class="reference internal" href="#asyncio.BufferedProtocol.buffer_updated" title="asyncio.BufferedProtocol.buffer_updated"><code>buffer_updated()</code></a> won’t be called after it.</p> <p>State machine:</p> <pre data-language="none">start -> connection_made
[-> get_buffer
[-> buffer_updated]?
]*
[-> eof_received]?
-> connection_lost -> end
</pre> </section> <section id="datagram-protocols"> <h3>Datagram Protocols</h3> <p>Datagram Protocol instances should be constructed by protocol factories passed to the <a class="reference internal" href="asyncio-eventloop#asyncio.loop.create_datagram_endpoint" title="asyncio.loop.create_datagram_endpoint"><code>loop.create_datagram_endpoint()</code></a> method.</p> <dl class="py method"> <dt class="sig sig-object py" id="asyncio.DatagramProtocol.datagram_received">
<code>DatagramProtocol.datagram_received(data, addr)</code> </dt> <dd>
<p>Called when a datagram is received. <em>data</em> is a bytes object containing the incoming data. <em>addr</em> is the address of the peer sending the data; the exact format depends on the transport.</p> </dd>
</dl> <dl class="py method"> <dt class="sig sig-object py" id="asyncio.DatagramProtocol.error_received">
<code>DatagramProtocol.error_received(exc)</code> </dt> <dd>
<p>Called when a previous send or receive operation raises an <a class="reference internal" href="exceptions#OSError" title="OSError"><code>OSError</code></a>. <em>exc</em> is the <a class="reference internal" href="exceptions#OSError" title="OSError"><code>OSError</code></a> instance.</p> <p>This method is called in rare conditions, when the transport (e.g. UDP) detects that a datagram could not be delivered to its recipient. In many conditions though, undeliverable datagrams will be silently dropped.</p> </dd>
</dl> <div class="admonition note"> <p class="admonition-title">Note</p> <p>On BSD systems (macOS, FreeBSD, etc.) flow control is not supported for datagram protocols, because there is no reliable way to detect send failures caused by writing too many packets.</p> <p>The socket always appears ‘ready’ and excess packets are dropped. An <a class="reference internal" href="exceptions#OSError" title="OSError"><code>OSError</code></a> with <code>errno</code> set to <a class="reference internal" href="errno#errno.ENOBUFS" title="errno.ENOBUFS"><code>errno.ENOBUFS</code></a> may or may not be raised; if it is raised, it will be reported to <a class="reference internal" href="#asyncio.DatagramProtocol.error_received" title="asyncio.DatagramProtocol.error_received"><code>DatagramProtocol.error_received()</code></a> but otherwise ignored.</p> </div> </section> <section id="subprocess-protocols"> <span id="asyncio-subprocess-protocols"></span><h3>Subprocess Protocols</h3> <p>Subprocess Protocol instances should be constructed by protocol factories passed to the <a class="reference internal" href="asyncio-eventloop#asyncio.loop.subprocess_exec" title="asyncio.loop.subprocess_exec"><code>loop.subprocess_exec()</code></a> and <a class="reference internal" href="asyncio-eventloop#asyncio.loop.subprocess_shell" title="asyncio.loop.subprocess_shell"><code>loop.subprocess_shell()</code></a> methods.</p> <dl class="py method"> <dt class="sig sig-object py" id="asyncio.SubprocessProtocol.pipe_data_received">
<code>SubprocessProtocol.pipe_data_received(fd, data)</code> </dt> <dd>
<p>Called when the child process writes data into its stdout or stderr pipe.</p> <p><em>fd</em> is the integer file descriptor of the pipe.</p> <p><em>data</em> is a non-empty bytes object containing the received data.</p> </dd>
</dl> <dl class="py method"> <dt class="sig sig-object py" id="asyncio.SubprocessProtocol.pipe_connection_lost">
<code>SubprocessProtocol.pipe_connection_lost(fd, exc)</code> </dt> <dd>
<p>Called when one of the pipes communicating with the child process is closed.</p> <p><em>fd</em> is the integer file descriptor that was closed.</p> </dd>
</dl> <dl class="py method"> <dt class="sig sig-object py" id="asyncio.SubprocessProtocol.process_exited">
<code>SubprocessProtocol.process_exited()</code> </dt> <dd>
<p>Called when the child process has exited.</p> <p>It can be called before <a class="reference internal" href="#asyncio.SubprocessProtocol.pipe_data_received" title="asyncio.SubprocessProtocol.pipe_data_received"><code>pipe_data_received()</code></a> and <a class="reference internal" href="#asyncio.SubprocessProtocol.pipe_connection_lost" title="asyncio.SubprocessProtocol.pipe_connection_lost"><code>pipe_connection_lost()</code></a> methods.</p> </dd>
</dl> </section> </section> <section id="examples"> <h2>Examples</h2> <section id="tcp-echo-server"> <span id="asyncio-example-tcp-echo-server-protocol"></span><h3>TCP Echo Server</h3> <p>Create a TCP echo server using the <a class="reference internal" href="asyncio-eventloop#asyncio.loop.create_server" title="asyncio.loop.create_server"><code>loop.create_server()</code></a> method, send back received data, and close the connection:</p> <pre data-language="python">import asyncio
class EchoServerProtocol(asyncio.Protocol):
def connection_made(self, transport):
peername = transport.get_extra_info('peername')
print('Connection from {}'.format(peername))
self.transport = transport
def data_received(self, data):
message = data.decode()
print('Data received: {!r}'.format(message))
print('Send: {!r}'.format(message))
self.transport.write(data)
print('Close the client socket')
self.transport.close()
async def main():
# Get a reference to the event loop as we plan to use
# low-level APIs.
loop = asyncio.get_running_loop()
server = await loop.create_server(
lambda: EchoServerProtocol(),
'127.0.0.1', 8888)
async with server:
await server.serve_forever()
asyncio.run(main())
</pre> <div class="admonition seealso"> <p class="admonition-title">See also</p> <p>The <a class="reference internal" href="asyncio-stream#asyncio-tcp-echo-server-streams"><span class="std std-ref">TCP echo server using streams</span></a> example uses the high-level <a class="reference internal" href="asyncio-stream#asyncio.start_server" title="asyncio.start_server"><code>asyncio.start_server()</code></a> function.</p> </div> </section> <section id="tcp-echo-client"> <span id="asyncio-example-tcp-echo-client-protocol"></span><h3>TCP Echo Client</h3> <p>A TCP echo client using the <a class="reference internal" href="asyncio-eventloop#asyncio.loop.create_connection" title="asyncio.loop.create_connection"><code>loop.create_connection()</code></a> method, sends data, and waits until the connection is closed:</p> <pre data-language="python">import asyncio
class EchoClientProtocol(asyncio.Protocol):
def __init__(self, message, on_con_lost):
self.message = message
self.on_con_lost = on_con_lost
def connection_made(self, transport):
transport.write(self.message.encode())
print('Data sent: {!r}'.format(self.message))
def data_received(self, data):
print('Data received: {!r}'.format(data.decode()))
def connection_lost(self, exc):
print('The server closed the connection')
self.on_con_lost.set_result(True)
async def main():
# Get a reference to the event loop as we plan to use
# low-level APIs.
loop = asyncio.get_running_loop()
on_con_lost = loop.create_future()
message = 'Hello World!'
transport, protocol = await loop.create_connection(
lambda: EchoClientProtocol(message, on_con_lost),
'127.0.0.1', 8888)
# Wait until the protocol signals that the connection
# is lost and close the transport.
try:
await on_con_lost
finally:
transport.close()
asyncio.run(main())
</pre> <div class="admonition seealso"> <p class="admonition-title">See also</p> <p>The <a class="reference internal" href="asyncio-stream#asyncio-tcp-echo-client-streams"><span class="std std-ref">TCP echo client using streams</span></a> example uses the high-level <a class="reference internal" href="asyncio-stream#asyncio.open_connection" title="asyncio.open_connection"><code>asyncio.open_connection()</code></a> function.</p> </div> </section> <section id="udp-echo-server"> <span id="asyncio-udp-echo-server-protocol"></span><h3>UDP Echo Server</h3> <p>A UDP echo server, using the <a class="reference internal" href="asyncio-eventloop#asyncio.loop.create_datagram_endpoint" title="asyncio.loop.create_datagram_endpoint"><code>loop.create_datagram_endpoint()</code></a> method, sends back received data:</p> <pre data-language="python">import asyncio
class EchoServerProtocol:
def connection_made(self, transport):
self.transport = transport
def datagram_received(self, data, addr):
message = data.decode()
print('Received %r from %s' % (message, addr))
print('Send %r to %s' % (message, addr))
self.transport.sendto(data, addr)
async def main():
print("Starting UDP server")
# Get a reference to the event loop as we plan to use
# low-level APIs.
loop = asyncio.get_running_loop()
# One protocol instance will be created to serve all
# client requests.
transport, protocol = await loop.create_datagram_endpoint(
lambda: EchoServerProtocol(),
local_addr=('127.0.0.1', 9999))
try:
await asyncio.sleep(3600) # Serve for 1 hour.
finally:
transport.close()
asyncio.run(main())
</pre> </section> <section id="udp-echo-client"> <span id="asyncio-udp-echo-client-protocol"></span><h3>UDP Echo Client</h3> <p>A UDP echo client, using the <a class="reference internal" href="asyncio-eventloop#asyncio.loop.create_datagram_endpoint" title="asyncio.loop.create_datagram_endpoint"><code>loop.create_datagram_endpoint()</code></a> method, sends data and closes the transport when it receives the answer:</p> <pre data-language="python">import asyncio
class EchoClientProtocol:
def __init__(self, message, on_con_lost):
self.message = message
self.on_con_lost = on_con_lost
self.transport = None
def connection_made(self, transport):
self.transport = transport
print('Send:', self.message)
self.transport.sendto(self.message.encode())
def datagram_received(self, data, addr):
print("Received:", data.decode())
print("Close the socket")
self.transport.close()
def error_received(self, exc):
print('Error received:', exc)
def connection_lost(self, exc):
print("Connection closed")
self.on_con_lost.set_result(True)
async def main():
# Get a reference to the event loop as we plan to use
# low-level APIs.
loop = asyncio.get_running_loop()
on_con_lost = loop.create_future()
message = "Hello World!"
transport, protocol = await loop.create_datagram_endpoint(
lambda: EchoClientProtocol(message, on_con_lost),
remote_addr=('127.0.0.1', 9999))
try:
await on_con_lost
finally:
transport.close()
asyncio.run(main())
</pre> </section> <section id="connecting-existing-sockets"> <span id="asyncio-example-create-connection"></span><h3>Connecting Existing Sockets</h3> <p>Wait until a socket receives data using the <a class="reference internal" href="asyncio-eventloop#asyncio.loop.create_connection" title="asyncio.loop.create_connection"><code>loop.create_connection()</code></a> method with a protocol:</p> <pre data-language="python">import asyncio
import socket
class MyProtocol(asyncio.Protocol):
def __init__(self, on_con_lost):
self.transport = None
self.on_con_lost = on_con_lost
def connection_made(self, transport):
self.transport = transport
def data_received(self, data):
print("Received:", data.decode())
# We are done: close the transport;
# connection_lost() will be called automatically.
self.transport.close()
def connection_lost(self, exc):
# The socket has been closed
self.on_con_lost.set_result(True)
async def main():
# Get a reference to the event loop as we plan to use
# low-level APIs.
loop = asyncio.get_running_loop()
on_con_lost = loop.create_future()
# Create a pair of connected sockets
rsock, wsock = socket.socketpair()
# Register the socket to wait for data.
transport, protocol = await loop.create_connection(
lambda: MyProtocol(on_con_lost), sock=rsock)
# Simulate the reception of data from the network.
loop.call_soon(wsock.send, 'abc'.encode())
try:
await protocol.on_con_lost
finally:
transport.close()
wsock.close()
asyncio.run(main())
</pre> <div class="admonition seealso"> <p class="admonition-title">See also</p> <p>The <a class="reference internal" href="asyncio-eventloop#asyncio-example-watch-fd"><span class="std std-ref">watch a file descriptor for read events</span></a> example uses the low-level <a class="reference internal" href="asyncio-eventloop#asyncio.loop.add_reader" title="asyncio.loop.add_reader"><code>loop.add_reader()</code></a> method to register an FD.</p> <p>The <a class="reference internal" href="asyncio-stream#asyncio-example-create-connection-streams"><span class="std std-ref">register an open socket to wait for data using streams</span></a> example uses high-level streams created by the <a class="reference internal" href="asyncio-stream#asyncio.open_connection" title="asyncio.open_connection"><code>open_connection()</code></a> function in a coroutine.</p> </div> </section> <section id="loop-subprocess-exec-and-subprocessprotocol"> <span id="asyncio-example-subprocess-proto"></span><h3>loop.subprocess_exec() and SubprocessProtocol</h3> <p>An example of a subprocess protocol used to get the output of a subprocess and to wait for the subprocess exit.</p> <p>The subprocess is created by the <a class="reference internal" href="asyncio-eventloop#asyncio.loop.subprocess_exec" title="asyncio.loop.subprocess_exec"><code>loop.subprocess_exec()</code></a> method:</p> <pre data-language="python">import asyncio
import sys
class DateProtocol(asyncio.SubprocessProtocol):
def __init__(self, exit_future):
self.exit_future = exit_future
self.output = bytearray()
self.pipe_closed = False
self.exited = False
def pipe_connection_lost(self, fd, exc):
self.pipe_closed = True
self.check_for_exit()
def pipe_data_received(self, fd, data):
self.output.extend(data)
def process_exited(self):
self.exited = True
# process_exited() method can be called before
# pipe_connection_lost() method: wait until both methods are
# called.
self.check_for_exit()
def check_for_exit(self):
if self.pipe_closed and self.exited:
self.exit_future.set_result(True)
async def get_date():
# Get a reference to the event loop as we plan to use
# low-level APIs.
loop = asyncio.get_running_loop()
code = 'import datetime; print(datetime.datetime.now())'
exit_future = asyncio.Future(loop=loop)
# Create the subprocess controlled by DateProtocol;
# redirect the standard output into a pipe.
transport, protocol = await loop.subprocess_exec(
lambda: DateProtocol(exit_future),
sys.executable, '-c', code,
stdin=None, stderr=None)
# Wait for the subprocess exit using the process_exited()
# method of the protocol.
await exit_future
# Close the stdout pipe.
transport.close()
# Read the output which was collected by the
# pipe_data_received() method of the protocol.
data = bytes(protocol.output)
return data.decode('ascii').rstrip()
date = asyncio.run(get_date())
print(f"Current date: {date}")
</pre> <p>See also the <a class="reference internal" href="asyncio-subprocess#asyncio-example-create-subprocess-exec"><span class="std std-ref">same example</span></a> written using high-level APIs.</p> </section> </section> <div class="_attribution">
<p class="_attribution-p">
© 2001–2023 Python Software Foundation<br>Licensed under the PSF License.<br>
<a href="https://docs.python.org/3.12/library/asyncio-protocol.html" class="_attribution-link">https://docs.python.org/3.12/library/asyncio-protocol.html</a>
</p>
</div>
|