| 1 |
Metadata-Version: 2.1 |
| 2 |
Name: aiofile |
| 3 |
Version: 3.9.0 |
| 4 |
Summary: Asynchronous file operations. |
| 5 |
Home-page: http://github.com/mosquito/aiofile |
| 6 |
License: Apache-2.0 |
| 7 |
Keywords: aio,python,asyncio,fileio,io |
| 8 |
Author: Dmitry Orlov |
| 9 |
Author-email: [email protected] |
| 10 |
Requires-Python: >=3.8,<4 |
| 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 |
| 23 |
Classifier: Programming Language :: Python :: 3.8 |
| 24 |
Classifier: Programming Language :: Python :: 3.9 |
| 25 |
Classifier: Programming Language :: Python :: 3.10 |
| 26 |
Classifier: Programming Language :: Python :: 3.11 |
| 27 |
Classifier: Programming Language :: Python :: 3.12 |
| 28 |
Classifier: Programming Language :: Python :: 3 :: Only |
| 29 |
Classifier: Programming Language :: Python :: 3.13 |
| 30 |
Classifier: Programming Language :: Python :: Implementation :: CPython |
| 31 |
Classifier: Topic :: Software Development :: Libraries |
| 32 |
Classifier: Topic :: System |
| 33 |
Classifier: Topic :: System :: Operating System |
| 34 |
Requires-Dist: caio (>=0.9.0,<0.10.0) |
| 35 |
Description-Content-Type: text/markdown |
| 36 |
|
| 37 |
# AIOFile |
| 38 |
|
| 39 |
[](https://github.com/mosquito/aiofile/actions?query=branch%3Amaster) [](https://pypi.python.org/pypi/aiofile/) [](https://pypi.python.org/pypi/aiofile/) [](https://pypi.python.org/pypi/aiofile/) [](https://pypi.python.org/pypi/aiofile/) [](https://coveralls.io/github/mosquito/aiofile?branch=master) |
| 40 |
|
| 41 |
Real asynchronous file operations with asyncio support. |
| 42 |
|
| 43 |
## Status |
| 44 |
|
| 45 |
Development - Stable |
| 46 |
|
| 47 |
## Features |
| 48 |
|
| 49 |
* Since version 2.0.0 using [caio](https://pypi.org/project/caio), which contains linux `libaio` and two |
| 50 |
thread-based implementations (c-based and pure-python). |
| 51 |
* AIOFile has no internal pointer. You should pass `offset` and |
| 52 |
`chunk_size` for each operation or use helpers (Reader or Writer). |
| 53 |
The simplest way is to use `async_open` for creating object with |
| 54 |
file-like interface. |
| 55 |
* For Linux using implementation based on [libaio](https://pagure.io/libaio). |
| 56 |
* For POSIX (MacOS X and optional Linux) using implementation |
| 57 |
based on [threadpool](https://github.com/mbrossard/threadpool/). |
| 58 |
* Otherwise using pure-python thread-based implementation. |
| 59 |
* Implementation chooses automatically depending on system compatibility. |
| 60 |
|
| 61 |
## Limitations |
| 62 |
|
| 63 |
* Linux native AIO implementation is not able to open special files. |
| 64 |
Asynchronous operations against special fs like `/proc/` `/sys/` are not |
| 65 |
supported by the kernel. It's not a aiofile's or caio issue. |
| 66 |
In these cases, you might switch to thread-based implementations |
| 67 |
(see [Troubleshooting](#troubleshooting) section). |
| 68 |
However, when used on supported file systems, the linux implementation has a |
| 69 |
smaller overhead and is preferred but it's not a silver bullet. |
| 70 |
|
| 71 |
## Code examples |
| 72 |
|
| 73 |
All code examples require Python 3.6+. |
| 74 |
|
| 75 |
### High-level API |
| 76 |
|
| 77 |
#### `async_open` helper |
| 78 |
|
| 79 |
Helper mimics python file-like objects, it returns file-like |
| 80 |
objects with similar but async methods. |
| 81 |
|
| 82 |
Supported methods: |
| 83 |
|
| 84 |
* `async def read(length = -1)` - reading chunk from file, when length is |
| 85 |
`-1`, will be reading file to the end. |
| 86 |
* `async def write(data)` - writing chunk to file |
| 87 |
* `def seek(offset)` - setting file pointer position |
| 88 |
* `def tell()` - returns current file pointer position |
| 89 |
* `async def readline(size=-1, newline="\n")` - read chunks until |
| 90 |
newline or EOF. Since version 3.7.0 `__aiter__` returns `LineReader`. |
| 91 |
|
| 92 |
This method is suboptimal for small lines because it doesn't reuse read buffer. |
| 93 |
When you want to read file by lines please avoid using `async_open` |
| 94 |
use `LineReader` instead. |
| 95 |
* `def __aiter__() -> LineReader` - iterator over lines. |
| 96 |
* `def iter_chunked(chunk_size: int = 32768) -> Reader` - iterator over |
| 97 |
chunks. |
| 98 |
* `.file` property contains AIOFile object |
| 99 |
|
| 100 |
Basic example: |
| 101 |
|
| 102 |
<!-- name: test_basic --> |
| 103 |
```python |
| 104 |
import asyncio |
| 105 |
from pathlib import Path |
| 106 |
from tempfile import gettempdir |
| 107 |
|
| 108 |
from aiofile import async_open |
| 109 |
|
| 110 |
tmp_filename = Path(gettempdir()) / "hello.txt" |
| 111 |
|
| 112 |
async def main(): |
| 113 |
async with async_open(tmp_filename, 'w+') as afp: |
| 114 |
await afp.write("Hello ") |
| 115 |
await afp.write("world") |
| 116 |
afp.seek(0) |
| 117 |
|
| 118 |
print(await afp.read()) |
| 119 |
|
| 120 |
await afp.write("Hello from\nasync world") |
| 121 |
print(await afp.readline()) |
| 122 |
print(await afp.readline()) |
| 123 |
|
| 124 |
asyncio.run(main()) |
| 125 |
``` |
| 126 |
|
| 127 |
Example without context manager: |
| 128 |
|
| 129 |
<!-- name: test_basic_without_context_manager --> |
| 130 |
```python |
| 131 |
import asyncio |
| 132 |
import atexit |
| 133 |
import os |
| 134 |
from tempfile import mktemp |
| 135 |
|
| 136 |
from aiofile import async_open |
| 137 |
|
| 138 |
|
| 139 |
TMP_NAME = mktemp() |
| 140 |
atexit.register(os.unlink, TMP_NAME) |
| 141 |
|
| 142 |
|
| 143 |
async def main(): |
| 144 |
afp = await async_open(TMP_NAME, "w") |
| 145 |
await afp.write("Hello") |
| 146 |
await afp.close() |
| 147 |
|
| 148 |
|
| 149 |
asyncio.run(main()) |
| 150 |
assert open(TMP_NAME, "r").read() == "Hello" |
| 151 |
``` |
| 152 |
|
| 153 |
Concatenate example program (`cat`): |
| 154 |
|
| 155 |
```python |
| 156 |
import asyncio |
| 157 |
import sys |
| 158 |
from argparse import ArgumentParser |
| 159 |
from pathlib import Path |
| 160 |
|
| 161 |
from aiofile import async_open |
| 162 |
|
| 163 |
parser = ArgumentParser( |
| 164 |
description="Read files line by line using asynchronous io API" |
| 165 |
) |
| 166 |
parser.add_argument("file_name", nargs="+", type=Path) |
| 167 |
|
| 168 |
async def main(arguments): |
| 169 |
for src in arguments.file_name: |
| 170 |
async with async_open(src, "r") as afp: |
| 171 |
async for line in afp: |
| 172 |
sys.stdout.write(line) |
| 173 |
|
| 174 |
|
| 175 |
asyncio.run(main(parser.parse_args())) |
| 176 |
``` |
| 177 |
|
| 178 |
Copy file example program (`cp`): |
| 179 |
|
| 180 |
```python |
| 181 |
import asyncio |
| 182 |
from argparse import ArgumentParser |
| 183 |
from pathlib import Path |
| 184 |
|
| 185 |
from aiofile import async_open |
| 186 |
|
| 187 |
parser = ArgumentParser( |
| 188 |
description="Copying files using asynchronous io API" |
| 189 |
) |
| 190 |
parser.add_argument("source", type=Path) |
| 191 |
parser.add_argument("dest", type=Path) |
| 192 |
parser.add_argument("--chunk-size", type=int, default=65535) |
| 193 |
|
| 194 |
|
| 195 |
async def main(arguments): |
| 196 |
async with async_open(arguments.source, "rb") as src, \ |
| 197 |
async_open(arguments.dest, "wb") as dest: |
| 198 |
async for chunk in src.iter_chunked(arguments.chunk_size): |
| 199 |
await dest.write(chunk) |
| 200 |
|
| 201 |
|
| 202 |
asyncio.run(main(parser.parse_args())) |
| 203 |
``` |
| 204 |
|
| 205 |
Example with opening already open file pointer: |
| 206 |
|
| 207 |
```python |
| 208 |
import asyncio |
| 209 |
from typing import IO, Any |
| 210 |
from aiofile import async_open |
| 211 |
|
| 212 |
|
| 213 |
async def main(fp: IO[Any]): |
| 214 |
async with async_open(fp) as afp: |
| 215 |
await afp.write("Hello from\nasync world") |
| 216 |
print(await afp.readline()) |
| 217 |
|
| 218 |
|
| 219 |
with open("test.txt", "w+") as fp: |
| 220 |
asyncio.run(main(fp)) |
| 221 |
``` |
| 222 |
|
| 223 |
Linux native aio doesn't support reading and writing special files |
| 224 |
(e.g. procfs/sysfs/unix pipes/etc.), so you can perform operations with |
| 225 |
these files using compatible context objects. |
| 226 |
|
| 227 |
```python |
| 228 |
import asyncio |
| 229 |
from aiofile import async_open |
| 230 |
from caio import thread_aio_asyncio |
| 231 |
from contextlib import AsyncExitStack |
| 232 |
|
| 233 |
|
| 234 |
async def main(): |
| 235 |
async with AsyncExitStack() as stack: |
| 236 |
|
| 237 |
# Custom context should be reused |
| 238 |
ctx = await stack.enter_async_context( |
| 239 |
thread_aio_asyncio.AsyncioContext() |
| 240 |
) |
| 241 |
|
| 242 |
# Open special file with custom context |
| 243 |
src = await stack.enter_async_context( |
| 244 |
async_open("/proc/cpuinfo", "r", context=ctx) |
| 245 |
) |
| 246 |
|
| 247 |
# Open regular file with default context |
| 248 |
dest = await stack.enter_async_context( |
| 249 |
async_open("/tmp/cpuinfo", "w") |
| 250 |
) |
| 251 |
|
| 252 |
# Copying file content line by line |
| 253 |
async for line in src: |
| 254 |
await dest.write(line) |
| 255 |
|
| 256 |
|
| 257 |
asyncio.run(main()) |
| 258 |
``` |
| 259 |
|
| 260 |
### Low-level API |
| 261 |
|
| 262 |
The `AIOFile` class is a low-level interface for asynchronous file operations, and the read and write methods accept |
| 263 |
an `offset=0` in bytes at which the operation will be performed. |
| 264 |
|
| 265 |
This allows you to do many independent IO operations on a once open file without moving the virtual carriage. |
| 266 |
|
| 267 |
For example, you may make 10 concurrent HTTP requests by specifying the `Range` header, and asynchronously write |
| 268 |
one opened file, while the offsets must either be calculated manually, or use 10 instances of `Writer` with |
| 269 |
specified initial offsets. |
| 270 |
|
| 271 |
In order to provide sequential reading and writing, there is `Writer`, `Reader` and `LineReader`. Keep in mind |
| 272 |
`async_open` is not the same as AIOFile, it provides a similar interface for file operations, it simulates methods |
| 273 |
like read or write as it is implemented in the built-in open. |
| 274 |
|
| 275 |
```python |
| 276 |
import asyncio |
| 277 |
from aiofile import AIOFile |
| 278 |
|
| 279 |
|
| 280 |
async def main(): |
| 281 |
async with AIOFile("hello.txt", 'w+') as afp: |
| 282 |
payload = "Hello world\n" |
| 283 |
|
| 284 |
await asyncio.gather( |
| 285 |
*[afp.write(payload, offset=i * len(payload)) for i in range(10)] |
| 286 |
) |
| 287 |
|
| 288 |
await afp.fsync() |
| 289 |
|
| 290 |
assert await afp.read(len(payload) * 10) == payload * 10 |
| 291 |
|
| 292 |
asyncio.run(main()) |
| 293 |
``` |
| 294 |
|
| 295 |
The Low-level API in fact is just little bit sugared `caio` API. |
| 296 |
|
| 297 |
```python |
| 298 |
import asyncio |
| 299 |
from aiofile import AIOFile |
| 300 |
|
| 301 |
|
| 302 |
async def main(): |
| 303 |
async with AIOFile("/tmp/hello.txt", 'w+') as afp: |
| 304 |
await afp.write("Hello ") |
| 305 |
await afp.write("world", offset=7) |
| 306 |
await afp.fsync() |
| 307 |
|
| 308 |
print(await afp.read()) |
| 309 |
|
| 310 |
|
| 311 |
asyncio.run(main()) |
| 312 |
``` |
| 313 |
|
| 314 |
#### `Reader` and `Writer` |
| 315 |
|
| 316 |
When you want to read or write file linearly following example |
| 317 |
might be helpful. |
| 318 |
|
| 319 |
```python |
| 320 |
import asyncio |
| 321 |
from aiofile import AIOFile, Reader, Writer |
| 322 |
|
| 323 |
|
| 324 |
async def main(): |
| 325 |
async with AIOFile("/tmp/hello.txt", 'w+') as afp: |
| 326 |
writer = Writer(afp) |
| 327 |
reader = Reader(afp, chunk_size=8) |
| 328 |
|
| 329 |
await writer("Hello") |
| 330 |
await writer(" ") |
| 331 |
await writer("World") |
| 332 |
await afp.fsync() |
| 333 |
|
| 334 |
async for chunk in reader: |
| 335 |
print(chunk) |
| 336 |
|
| 337 |
|
| 338 |
asyncio.run(main()) |
| 339 |
``` |
| 340 |
|
| 341 |
#### `LineReader` - read file line by line |
| 342 |
|
| 343 |
LineReader is a helper that is very effective when you want to read a file |
| 344 |
linearly and line by line. |
| 345 |
|
| 346 |
It contains a buffer and will read the fragments of the file chunk by |
| 347 |
chunk into the buffer, where it will try to find lines. |
| 348 |
|
| 349 |
The default chunk size is 4KB. |
| 350 |
|
| 351 |
```python |
| 352 |
import asyncio |
| 353 |
from aiofile import AIOFile, LineReader, Writer |
| 354 |
|
| 355 |
|
| 356 |
async def main(): |
| 357 |
async with AIOFile("/tmp/hello.txt", 'w+') as afp: |
| 358 |
writer = Writer(afp) |
| 359 |
|
| 360 |
await writer("Hello") |
| 361 |
await writer(" ") |
| 362 |
await writer("World") |
| 363 |
await writer("\n") |
| 364 |
await writer("\n") |
| 365 |
await writer("From async world") |
| 366 |
await afp.fsync() |
| 367 |
|
| 368 |
async for line in LineReader(afp): |
| 369 |
print(line) |
| 370 |
|
| 371 |
|
| 372 |
asyncio.run(main()) |
| 373 |
``` |
| 374 |
|
| 375 |
When you want to read file by lines please avoid to use `async_open` |
| 376 |
use `LineReader` instead. |
| 377 |
|
| 378 |
## More examples |
| 379 |
|
| 380 |
Useful examples with `aiofile` |
| 381 |
|
| 382 |
### Async CSV Dict Reader |
| 383 |
|
| 384 |
```python |
| 385 |
import asyncio |
| 386 |
import io |
| 387 |
from csv import DictReader |
| 388 |
|
| 389 |
from aiofile import AIOFile, LineReader |
| 390 |
|
| 391 |
|
| 392 |
class AsyncDictReader: |
| 393 |
def __init__(self, afp, **kwargs): |
| 394 |
self.buffer = io.BytesIO() |
| 395 |
self.file_reader = LineReader( |
| 396 |
afp, line_sep=kwargs.pop('line_sep', '\n'), |
| 397 |
chunk_size=kwargs.pop('chunk_size', 4096), |
| 398 |
offset=kwargs.pop('offset', 0), |
| 399 |
) |
| 400 |
self.reader = DictReader( |
| 401 |
io.TextIOWrapper( |
| 402 |
self.buffer, |
| 403 |
encoding=kwargs.pop('encoding', 'utf-8'), |
| 404 |
errors=kwargs.pop('errors', 'replace'), |
| 405 |
), **kwargs, |
| 406 |
) |
| 407 |
self.line_num = 0 |
| 408 |
|
| 409 |
def __aiter__(self): |
| 410 |
return self |
| 411 |
|
| 412 |
async def __anext__(self): |
| 413 |
if self.line_num == 0: |
| 414 |
header = await self.file_reader.readline() |
| 415 |
self.buffer.write(header) |
| 416 |
|
| 417 |
line = await self.file_reader.readline() |
| 418 |
|
| 419 |
if not line: |
| 420 |
raise StopAsyncIteration |
| 421 |
|
| 422 |
self.buffer.write(line) |
| 423 |
self.buffer.seek(0) |
| 424 |
|
| 425 |
try: |
| 426 |
result = next(self.reader) |
| 427 |
except StopIteration as e: |
| 428 |
raise StopAsyncIteration from e |
| 429 |
|
| 430 |
self.buffer.seek(0) |
| 431 |
self.buffer.truncate(0) |
| 432 |
self.line_num = self.reader.line_num |
| 433 |
|
| 434 |
return result |
| 435 |
|
| 436 |
|
| 437 |
async def main(): |
| 438 |
async with AIOFile('sample.csv', 'rb') as afp: |
| 439 |
async for item in AsyncDictReader(afp): |
| 440 |
print(item) |
| 441 |
|
| 442 |
|
| 443 |
asyncio.run(main()) |
| 444 |
``` |
| 445 |
|
| 446 |
## Troubleshooting |
| 447 |
|
| 448 |
The caio `linux` implementation works normal for modern linux kernel versions |
| 449 |
and file systems. So you may have problems specific for your environment. |
| 450 |
It's not a bug and might be resolved some ways: |
| 451 |
|
| 452 |
1. Upgrade the kernel |
| 453 |
2. Use compatible file systems |
| 454 |
3. Use threads based or pure python implementation. |
| 455 |
|
| 456 |
The caio since version 0.7.0 contains some ways to do this. |
| 457 |
|
| 458 |
1. In runtime use the environment variable `CAIO_IMPL` with |
| 459 |
possible values: |
| 460 |
|
| 461 |
* `linux` - use native linux kernels aio mechanism |
| 462 |
* `thread` - use thread based implementation written in C |
| 463 |
* `python` - use pure python implementation |
| 464 |
|
| 465 |
2. File `default_implementation` located near `__init__.py` in caio |
| 466 |
installation path. It's useful for distros package maintainers. This file |
| 467 |
might contains comments (lines starts with `#` symbol) and the first line |
| 468 |
should be one of `linux` `thread` or `python`. |
| 469 |
|
| 470 |
3. You might manually manage contexts: |
| 471 |
|
| 472 |
```python |
| 473 |
import asyncio |
| 474 |
|
| 475 |
from aiofile import async_open |
| 476 |
from caio import linux_aio_asyncio, thread_aio_asyncio |
| 477 |
|
| 478 |
|
| 479 |
async def main(): |
| 480 |
linux_ctx = linux_aio_asyncio.AsyncioContext() |
| 481 |
threads_ctx = thread_aio_asyncio.AsyncioContext() |
| 482 |
|
| 483 |
async with async_open("/tmp/test.txt", "w", context=linux_ctx) as afp: |
| 484 |
await afp.write("Hello") |
| 485 |
|
| 486 |
async with async_open("/tmp/test.txt", "r", context=threads_ctx) as afp: |
| 487 |
print(await afp.read()) |
| 488 |
|
| 489 |
|
| 490 |
asyncio.run(main()) |
| 491 |
``` |
| 492 |
|