Debian Codegraph @

PKG-INFO

raw
1 Metadata-Version: 2.4
2 Name: aiofile
3 Version: 3.12.3
4 Summary: Asynchronous file operations.
5 Project-URL: Homepage, https://github.com/mosquito/aiofile
6 Author-email: Dmitry Orlov <[email protected]>
7 License-Expression: Apache-2.0
8 License-File: LICENCE
9 License-File: LICENCE.md
10 Keywords: aio,asyncio,fileio,io,python
11 Classifier: Development Status :: 5 - Production/Stable
12 Classifier: Environment :: Console
13 Classifier: Intended Audience :: Developers
14 Classifier: Intended Audience :: Education
15 Classifier: Intended Audience :: End Users/Desktop
16 Classifier: License :: OSI Approved :: Apache Software License
17 Classifier: Natural Language :: English
18 Classifier: Natural Language :: Russian
19 Classifier: Operating System :: MacOS :: MacOS X
20 Classifier: Operating System :: POSIX :: Linux
21 Classifier: Programming Language :: Python
22 Classifier: Programming Language :: Python :: 3 :: Only
23 Classifier: Programming Language :: Python :: 3.11
24 Classifier: Programming Language :: Python :: 3.12
25 Classifier: Programming Language :: Python :: 3.13
26 Classifier: Programming Language :: Python :: 3.14
27 Classifier: Programming Language :: Python :: Implementation :: CPython
28 Classifier: Topic :: Software Development :: Libraries
29 Classifier: Topic :: System
30 Classifier: Topic :: System :: Operating System
31 Requires-Python: >=3.11
32 Requires-Dist: caio~=0.12.0
33 Description-Content-Type: text/markdown
34
35 # AIOFile
36
37 [![Github Actions](https://github.com/mosquito/aiofile/workflows/ci/badge.svg)](https://github.com/mosquito/aiofile/actions?query=workflow%3Aci) [![Latest Version](https://img.shields.io/pypi/v/aiofile.svg)](https://pypi.python.org/pypi/aiofile/) [![Python Versions](https://img.shields.io/pypi/pyversions/aiofile.svg)](https://pypi.python.org/pypi/aiofile/) [![License](https://img.shields.io/pypi/l/aiofile.svg)](https://pypi.python.org/pypi/aiofile/) [![Coverage Status](https://coveralls.io/repos/github/mosquito/aiofile/badge.svg?branch=master)](https://coveralls.io/github/mosquito/aiofile?branch=master)
38
39 Real asynchronous file operations with asyncio support.
40
41 ## Features
42
43 * Since version 2.0.0, uses [caio](https://pypi.org/project/caio), which provides multiple
44 async I/O backends:
45 * **Linux io_uring** — the modern, high-performance Linux kernel AIO interface.
46 * **Linux libaio** — the classic kernel AIO mechanism via [libaio](https://pagure.io/libaio).
47 * **Thread-based (C)** — a [threadpool](https://github.com/mbrossard/threadpool/)-backed
48 implementation for POSIX systems (macOS, Linux).
49 * **Pure Python** — a thread-based fallback for any platform.
50 * The best available backend is chosen automatically based on system compatibility.
51 * `AIOFile` has no internal file pointer. Pass `offset` and `chunk_size` to each operation,
52 or use the `Reader`/`Writer` helpers. For a file-like interface, use `async_open`.
53
54 ## Limitations
55
56 * The Linux native AIO and io_uring backends cannot open special files.
57 Asynchronous operations against special filesystems such as `/proc/` or `/sys/` are not
58 supported by the kernel — this is neither an aiofile nor a caio issue.
59 In such cases, switch to a thread-based implementation
60 (see the [Troubleshooting](#troubleshooting) section).
61
62 ## Code examples
63
64 All code examples require Python 3.11+.
65
66 ### High-level API
67
68 #### `async_open` helper
69
70 This helper mimics Python's file-like objects, returning an object with
71 equivalent asynchronous methods.
72
73 Supported methods:
74
75 * `async def read(length=-1)` — reads a chunk from the file; `-1` reads to the end.
76 * `async def write(data)` — writes a chunk to the file.
77 * `def seek(offset)` — sets the file pointer position.
78 * `def tell()` — returns the current file pointer position.
79 * `async def readline(size=-1, newline="\n")` — reads until a newline or EOF.
80 Since version 3.7.0, `__aiter__` returns a `LineReader`.
81 This method is suboptimal for small lines because it does not reuse the read buffer —
82 prefer `LineReader` when reading line by line.
83 * `def __aiter__() -> LineReader` — iterator over lines.
84 * `def iter_chunked(chunk_size: int = 32768) -> Reader` — iterator over chunks.
85 * `.file` — the underlying `AIOFile` object.
86
87 Basic example:
88
89 <!-- name: test_basic -->
90 ```python
91 import asyncio
92 from pathlib import Path
93 from tempfile import gettempdir
94
95 from aiofile import async_open
96
97 tmp_filename = Path(gettempdir()) / "hello.txt"
98
99 async def main():
100 async with async_open(tmp_filename, 'w+') as afp:
101 await afp.write("Hello ")
102 await afp.write("world")
103 afp.seek(0)
104
105 print(await afp.read())
106
107 await afp.write("Hello from\nasync world")
108 print(await afp.readline())
109 print(await afp.readline())
110
111 asyncio.run(main())
112 ```
113
114 Example without context manager:
115
116 <!-- name: test_basic_without_context_manager -->
117 ```python
118 import asyncio
119 import atexit
120 import os
121 from tempfile import mktemp
122
123 from aiofile import async_open
124
125
126 TMP_NAME = mktemp()
127 atexit.register(os.unlink, TMP_NAME)
128
129
130 async def main():
131 afp = await async_open(TMP_NAME, "w")
132 await afp.write("Hello")
133 await afp.close()
134
135
136 asyncio.run(main())
137 assert open(TMP_NAME, "r").read() == "Hello"
138 ```
139
140 Concatenate example program (`cat`):
141
142 ```python
143 import asyncio
144 import sys
145 from argparse import ArgumentParser
146 from pathlib import Path
147
148 from aiofile import async_open
149
150 parser = ArgumentParser(
151 description="Read files line by line using asynchronous io API"
152 )
153 parser.add_argument("file_name", nargs="+", type=Path)
154
155 async def main(arguments):
156 for src in arguments.file_name:
157 async with async_open(src, "r") as afp:
158 async for line in afp:
159 sys.stdout.write(line)
160
161
162 asyncio.run(main(parser.parse_args()))
163 ```
164
165 Copy file example program (`cp`):
166
167 ```python
168 import asyncio
169 from argparse import ArgumentParser
170 from pathlib import Path
171
172 from aiofile import async_open
173
174 parser = ArgumentParser(
175 description="Copying files using asynchronous io API"
176 )
177 parser.add_argument("source", type=Path)
178 parser.add_argument("dest", type=Path)
179 parser.add_argument("--chunk-size", type=int, default=65535)
180
181
182 async def main(arguments):
183 async with async_open(arguments.source, "rb") as src, \
184 async_open(arguments.dest, "wb") as dest:
185 async for chunk in src.iter_chunked(arguments.chunk_size):
186 await dest.write(chunk)
187
188
189 asyncio.run(main(parser.parse_args()))
190 ```
191
192 Example with opening an already-open file pointer:
193
194 ```python
195 import asyncio
196 from typing import IO, Any
197 from aiofile import async_open
198
199
200 async def main(fp: IO[Any]):
201 async with async_open(fp) as afp:
202 await afp.write("Hello from\nasync world")
203 print(await afp.readline())
204
205
206 with open("test.txt", "w+") as fp:
207 asyncio.run(main(fp))
208 ```
209
210 Linux native AIO and io_uring do not support reading or writing special files
211 (procfs, sysfs, Unix pipes, etc.), so operations on these files require
212 a compatible context object.
213
214 ```python
215 import asyncio
216 from aiofile import async_open
217 from caio import thread_aio_asyncio
218 from contextlib import AsyncExitStack
219
220
221 async def main():
222 async with AsyncExitStack() as stack:
223
224 # Custom context should be reused
225 ctx = await stack.enter_async_context(
226 thread_aio_asyncio.AsyncioContext()
227 )
228
229 # Open special file with custom context
230 src = await stack.enter_async_context(
231 async_open("/proc/cpuinfo", "r", context=ctx)
232 )
233
234 # Open regular file with default context
235 dest = await stack.enter_async_context(
236 async_open("/tmp/cpuinfo", "w")
237 )
238
239 # Copying file content line by line
240 async for line in src:
241 await dest.write(line)
242
243
244 asyncio.run(main())
245 ```
246
247 ### `clone` helper
248
249 An asynchronous context supports a limited number of concurrent operations at the low level,
250 regardless of how many file descriptors are open. `clone` lets you create a second file-like
251 object with its own independent offset from a single descriptor, without opening the file
252 multiple times.
253
254 ```python
255 """
256 This example counts multiple hash functions from the file passed as the first
257 argument. The hash functions are counted competitively, and the results are
258 printed in the order of hashing completion.
259 """
260 import asyncio
261 import hashlib
262 import sys
263
264 import aiofile
265
266
267 async def hasher(name, hash_func, afp):
268 loop = asyncio.get_running_loop()
269 async for chunk in afp.iter_chunked(2 ** 20):
270 await loop.run_in_executor(None, hash_func.update, chunk)
271 print(name, hash_func.hexdigest())
272
273
274 async def main():
275 async with aiofile.async_open(sys.argv[1], "rb") as source:
276 hashers = [
277 ("MD5", hashlib.md5()),
278 ("SHA1", hashlib.sha1()),
279 ("SHA256", hashlib.sha256()),
280 ("SHA512", hashlib.sha512()),
281 ]
282
283 await asyncio.gather(*[
284 hasher(name, hash_func, await aiofile.clone(source))
285 for name, hash_func in hashers
286 ])
287
288
289 asyncio.run(main())
290 ```
291
292 > **Note:** This will likely perform poorly on Windows, so if that is
293 > your target platform, this optimization may not be worth it.
294
295 ### Low-level API
296
297 The `AIOFile` class is a low-level interface for asynchronous file operations. Its `read` and
298 `write` methods accept an `offset=0` (in bytes) at which the operation is performed.
299
300 This allows many independent I/O operations on a single open file without an internal pointer.
301 For sequential reading and writing, use `Writer`, `Reader`, and `LineReader`. Note that
302 `async_open` is not the same as `AIOFile`: it wraps it to provide a file-like interface
303 similar to the built-in `open`.
304
305 ```python
306 import asyncio
307 from aiofile import AIOFile
308
309
310 async def main():
311 async with AIOFile("hello.txt", 'w+') as afp:
312 payload = "Hello world\n"
313
314 await asyncio.gather(
315 *[afp.write(payload, offset=i * len(payload)) for i in range(10)]
316 )
317
318 await afp.fsync()
319
320 assert await afp.read(len(payload) * 10) == payload * 10
321
322 asyncio.run(main())
323 ```
324
325 The low-level API is essentially a lightly sugared `caio` API.
326
327 ```python
328 import asyncio
329 from aiofile import AIOFile
330
331
332 async def main():
333 async with AIOFile("/tmp/hello.txt", 'w+') as afp:
334 await afp.write("Hello ")
335 await afp.write("world", offset=7)
336 await afp.fsync()
337
338 print(await afp.read())
339
340
341 asyncio.run(main())
342 ```
343
344 #### `Reader` and `Writer`
345
346 To read or write a file linearly, the following example may be helpful.
347
348 ```python
349 import asyncio
350 from aiofile import AIOFile, Reader, Writer
351
352
353 async def main():
354 async with AIOFile("/tmp/hello.txt", 'w+') as afp:
355 writer = Writer(afp)
356 reader = Reader(afp, chunk_size=8)
357
358 await writer("Hello")
359 await writer(" ")
360 await writer("World")
361 await afp.fsync()
362
363 async for chunk in reader:
364 print(chunk)
365
366
367 asyncio.run(main())
368 ```
369
370 #### `LineReader` - read file line by line
371
372 `LineReader` is a helper for reading a file linearly, line by line. It maintains a buffer
373 and reads file fragments chunk by chunk, searching for line boundaries. The default chunk
374 size is 4KB.
375
376 ```python
377 import asyncio
378 from aiofile import AIOFile, LineReader, Writer
379
380
381 async def main():
382 async with AIOFile("/tmp/hello.txt", 'w+') as afp:
383 writer = Writer(afp)
384
385 await writer("Hello")
386 await writer(" ")
387 await writer("World")
388 await writer("\n")
389 await writer("\n")
390 await writer("From async world")
391 await afp.fsync()
392
393 async for line in LineReader(afp):
394 print(line)
395
396
397 asyncio.run(main())
398 ```
399
400 To read a file line by line, prefer `LineReader` over `async_open`.
401
402 ## More examples
403
404 ### Async CSV Dict Reader
405
406 ```python
407 import asyncio
408 import io
409 from csv import DictReader
410
411 from aiofile import AIOFile, LineReader
412
413
414 class AsyncDictReader:
415 def __init__(self, afp, **kwargs):
416 self.buffer = io.BytesIO()
417 self.file_reader = LineReader(
418 afp, line_sep=kwargs.pop('line_sep', '\n'),
419 chunk_size=kwargs.pop('chunk_size', 4096),
420 offset=kwargs.pop('offset', 0),
421 )
422 self.reader = DictReader(
423 io.TextIOWrapper(
424 self.buffer,
425 encoding=kwargs.pop('encoding', 'utf-8'),
426 errors=kwargs.pop('errors', 'replace'),
427 ), **kwargs,
428 )
429 self.line_num = 0
430
431 def __aiter__(self):
432 return self
433
434 async def __anext__(self):
435 if self.line_num == 0:
436 header = await self.file_reader.readline()
437 self.buffer.write(header)
438
439 line = await self.file_reader.readline()
440
441 if not line:
442 raise StopAsyncIteration
443
444 self.buffer.write(line)
445 self.buffer.seek(0)
446
447 try:
448 result = next(self.reader)
449 except StopIteration as e:
450 raise StopAsyncIteration from e
451
452 self.buffer.seek(0)
453 self.buffer.truncate(0)
454 self.line_num = self.reader.line_num
455
456 return result
457
458
459 async def main():
460 async with AIOFile('sample.csv', 'rb') as afp:
461 async for item in AsyncDictReader(afp):
462 print(item)
463
464
465 asyncio.run(main())
466 ```
467
468 ## Troubleshooting
469
470 The caio Linux backends (io_uring and libaio) work well on modern kernels and filesystems.
471 Problems are usually environment-specific and are not bugs. There are several ways to resolve them:
472
473 1. Upgrade the kernel.
474 2. Use a compatible filesystem.
475 3. Switch to a thread-based or pure-Python backend.
476
477 Since version 0.7.0, caio offers several ways to select the backend:
478
479 1. Set the `CAIO_IMPL` environment variable at runtime:
480
481 * `uring` — Linux io_uring (requires kernel ≥ 5.1)
482 * `linux` — Linux libaio
483 * `thread` — C-based thread pool implementation
484 * `python` — pure-Python thread-based fallback
485
486 2. The `default_implementation` file located next to `__init__.py` in the caio installation
487 directory. Useful for distribution package maintainers. The file may contain comments
488 (lines starting with `#`); the first non-comment line should be one of the values above.
489
490 3. Manage contexts manually:
491
492 ```python
493 import asyncio
494
495 from aiofile import async_open
496 from caio import linux_aio_asyncio, thread_aio_asyncio
497
498
499 async def main():
500 linux_ctx = linux_aio_asyncio.AsyncioContext()
501 threads_ctx = thread_aio_asyncio.AsyncioContext()
502
503 async with async_open("/tmp/test.txt", "w", context=linux_ctx) as afp:
504 await afp.write("Hello")
505
506 async with async_open("/tmp/test.txt", "r", context=threads_ctx) as afp:
507 print(await afp.read())
508
509
510 asyncio.run(main())
511 ```
512
513 ## Benchmark
514
515 stdlib, `aiofile` (once per `caio` backend, each in its own subprocess), `aiofiles`,
516 `aiomisc.io` — linear/random block order, read/write, buffered/`O_DIRECT`,
517 sequential/concurrent, fixed op count per cell (never a partial/cancelled
518 measurement). Tool, methodology and raw data: [`benchmark/`](benchmark/); a
519 third report at 4096B lives in `benchmark/results/`.
520
521 ![aiofile benchmark, 65536B blocks](https://media.githubusercontent.com/media/mosquito/aiofile/master/benchmark/results/aiofile-bench-report-bs65536.png)
522
523 Linear write, one Linux/ext4 run, 65536B blocks, 2000 ops/cell, per-op
524 latency in ms (p50 / p95, ±stdev):
525
526 | participant | x1 | x8 |
527 |-----------------------|------------------------|------------------------|
528 | stdlib (buffered) | 0.081 / 0.128 (±0.030) | 0.167 / 0.298 (±0.157) |
529 | stdlib (O_DIRECT) | 0.148 / 0.398 (±0.097) | 0.266 / 0.650 (±0.192) |
530 | aiofile (linux_uring) | 0.050 / 0.108 (±0.022) | 0.040 / 0.248 (±0.293) |
531 | aiofile (linux_aio) | 0.009 / 0.024 (±0.020) | 0.040 / 0.089 (±0.020) |
532 | aiofile (thread_aio) | 0.150 / 0.461 (±0.128) | 0.664 / 2.930 (±0.943) |
533 | aiofile (python_aio) | 0.109 / 0.173 (±0.042) | 0.189 / 0.314 (±0.072) |
534 | aiofiles | 0.155 / 0.257 (±0.175) | 1.166 / 2.238 (±0.570) |
535 | aiomisc | 0.156 / 0.256 (±0.051) | 1.118 / 1.607 (±1.750) |
536
537 `linux_aio` posts the lowest, tightest per-op latency at both concurrency
538 levels here -- `io_submit()` is a lean, purpose-built syscall, while
539 `linux_uring`'s ring/SQPOLL machinery is built to amortize *over batched
540 submissions*, not to minimize one op's latency, so it only pulls ahead
541 once there's a batch to amortize over. `aiofiles`/`aiomisc` latency
542 *grows* at x8 (one seek cursor, serialized by a lock) instead of
543 shrinking like the positional-I/O libraries.
544
545 ![aiofile benchmark, 256B blocks](https://media.githubusercontent.com/media/mosquito/aiofile/master/benchmark/results/aiofile-bench-report-bs256.png)
546
547 Linear write, 256B blocks, 2000 ops/cell, per-op latency in ms (p50 / p95, ±stdev):
548
549 | participant | x1 | x8 |
550 |-----------------------|-------------------------------|------------------------|
551 | stdlib (buffered) | 0.066 / 0.104 (±0.017) | 0.152 / 0.299 (±0.125) |
552 | stdlib (O_DIRECT) | n/a (256B isn't 4096-aligned) | n/a |
553 | aiofile (linux_uring) | 0.086 / 0.159 (±0.043) | 0.043 / 0.070 (±0.021) |
554 | aiofile (linux_aio) | 0.005 / 0.008 (±0.004) | 0.017 / 0.027 (±0.008) |
555 | aiofile (thread_aio) | 0.128 / 0.290 (±0.090) | 0.464 / 1.503 (±0.470) |
556 | aiofile (python_aio) | 0.113 / 0.201 (±0.037) | 0.179 / 0.354 (±0.124) |
557 | aiofiles | 0.136 / 0.169 (±0.030) | 1.002 / 1.516 (±0.372) |
558 | aiomisc | 0.144 / 0.223 (±0.040) | 1.046 / 1.999 (±0.415) |
559
560 Same shape at a tiny block size: `linux_aio` still has the lowest latency
561 by a wide margin (sub-10μs median at x1), `linux_uring` still needs
562 concurrency to close the gap (and still doesn't fully close it), and the
563 lock-serialized libraries still get *worse*, not better, under
564 concurrency.