trio
trio copied to clipboard
[Question] What is the best way to create temp files and directories?
Normally I would use tempfile
module.
But I was wondering if there's an async (trio compatible) alternative.
Thanks in advance
I'd do it like this. The file is still opened / created synchronously but writes are done async.
import tempfile
import trio
async def temp_file():
my_file = tempfile.TemporaryFile()
async with trio.wrap_file(my_file):
await my_file.write('Yo')
I guess I'll take a stab. Hopefully someone has already implemented this and worked out all the kinks that must certainly exist (and will chime in...). For example, I don't know what context manager bits of this would pass through sensibly or not.
https://github.com/python-trio/trio/blob/v0.18.0/trio/_file_io.py#L76-L79
import functools
import tempfile
import trio
async def temporary_file(*args, **kwargs):
sync_fn = partial(tempfile.TemporaryFile, *args, **kwargs)
sync_file = await trio.to_thread.run_sync(sync_fn)
return trio.wrap_file(sync_file)
Could decorate it as a wrapper but it appears that, in addition to being private, trio._util.async_wrap()
is exclusively for methods.
https://github.com/python-trio/trio/blob/v0.18.0/trio/_util.py#L200-L215