writeback_file¶
Files whose content is written back on close.
This module provides WritebackFile, a wrapper around a stream which invokes a user provided callback -- typically to persist the stream content -- when the file is closed.
WritebackFile
¶
A stream wrapper which persists its content on close.
The wrapped stream is closed by invoking the configured writeback function -- typically uploading or saving the data -- either explicitly via close(), on context exit, or when the wrapper is garbage collected.
Example
import io
from py_misc_utils import writeback_file as wbf
src = io.StringIO()
saved = []
with wbf.WritebackFile(src, lambda stream: saved.append(stream.getvalue())) as wf:
wf.write('hello')
print(saved) # ['hello']
print(src.closed) # True
# detach() closes the stream without running the writeback:
src2 = io.StringIO()
dropped = []
wf2 = wbf.WritebackFile(src2, lambda stream: dropped.append(stream.getvalue()))
wf2.detach()
print(dropped) # []
print(src2.closed) # True
Source code in py_misc_utils/writeback_file.py
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 | |
close(run_writeback=True)
¶
Close the wrapper, optionally running the writeback callback.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
run_writeback
|
If True, invoke the writeback callback with the stream; otherwise just close the stream, discarding the writeback. |
True
|
Source code in py_misc_utils/writeback_file.py
73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 | |
detach()
¶
Close the wrapper without running the writeback callback.
Source code in py_misc_utils/writeback_file.py
90 91 92 | |