StringIO Buffers Text Streams In Memory
io.StringIO wraps a string as an in-memory text stream, so print(file=...) and csv writers redirect into a buffer instead of touching the filesystem.
Code
from io import StringIO
import csv
# StringIO 把字符串包成内存里的文本流:凡是收 file 的 API 都能直接用
buffer = StringIO()
print("deploy log", file=buffer)
print("status: ok", file=buffer)
print("cursor after writes:", buffer.tell())
# 读完要先把游标拨回 0,read 才从头开始
buffer.seek(0)
content = buffer.read()
print("read() length:", len(content))
print(content, end="")
# csv 模块写出的行直接落在流里,不落盘
out = StringIO()
writer = csv.writer(out)
writer.writerow(["service", "ms"])
writer.writerow(["billing", 412])
print("csv payload lines:", out.getvalue().splitlines())
# print(file=...) 同样把输出重定向进流
sink = StringIO()
print("captured line", file=sink)
print("captured:", sink.getvalue().strip())Output
Captured from a sandboxed run of this snippet in the build pipeline.
cursor after writes: 22
read() length: 22
deploy log
status: ok
csv payload lines: ['service,ms', 'billing,412']
captured: captured lineHow the snippet works
Top-level bindings buffer, content, out, writer hold the demo state — nothing sits inside a function scope.
Applying it
The run emits 7 labeled sections — deploy log, status: ok, cursor after writes:, read() length:, csv payload lines:, captured line, captured: — one per step.
Interactive Tools for This Topic
A/B Test Sample Size CalculatorCalculate required per-variant sample size and experiment duration for two-proportion A/B tests from baseline conversion, MDE, alpha, and statistical power.JSONPath TesterTest JSONPath expressions against JSON documents with dot notation, brackets, wildcards, and recursive descent.Kubernetes Resource CalculatorCalculate per-pod and cluster CPU and memory requests, limits, QoS class, overcommit ratios, headroom, and node fit estimates for Kubernetes workloads.SRI Hash GeneratorGenerate Subresource Integrity (SRI) hashes from resource content using SHA-256, SHA-384, or SHA-512, and copy a ready-to-use script tag.
FAQ
- Is a package install part of the setup?
- No. Installation is unnecessary because only built-in APIs are used. Every import resolves inside the standard library — `io`, `csv`. Its state lives in module-level bindings: `buffer`, `content`, `out`.
Report a problem with this exampleOpens a pre-filled issue on GitHub.