实现说明
顶层就这几处状态:stream。
使用要点
- 只跑在标准库上;没有要装的东西。
- 跑完文件,输出里会留下标记——
locked while view open:、final bytes:。
常见问题
运行时需要 npm、pip、cargo 之类帮忙吗?
不需要——包管理器在这里无事可做,没有任何声明。 全部导入都来自标准库:io。 文件用顶层绑定保存自己的状态:stream。
核心语句
with stream.getbuffer() as view:
view[4:8] = b"0042"
try:
# Resizing writes fail with BufferError while an exported view is still alive
stream.write(b"-TAIL")
except BufferError as exc:
print("locked while view open:", exc)
代码示例
import io
stream = io.BytesIO(b"PKT-0000-READY")
# getbuffer() exports a writable memoryview directly over the internal buffer
with stream.getbuffer() as view:
view[4:8] = b"0042"
try:
# Resizing writes fail with BufferError while an exported view is still alive
stream.write(b"-TAIL")
except BufferError as exc:
print("locked while view open:", exc)
# Once the memoryview context exits, resizing writes work again
stream.seek(0, io.SEEK_END)
stream.write(b"-OK")
print("final bytes:", stream.getvalue().decode("ascii"))