存在一个问题How to write binary data to stdout in python 3?,但所有的答案都表明sys.stdout.buffer
或其变体(例如,手动重写文件描述符),它们有一个问题:它们不尊重缓冲:
MacBook-Pro-116:~ ezyang$ cat test.py
import sys
sys.stdout.write("A")
sys.stdout.buffer.write(b"B")
MacBook-Pro-116:~ ezyang$ python3 test.py | cat
BA
有没有一种方法可以将二进制数据写入stdout,同时考虑到sys.stdout
和未加修饰的print
语句的缓冲?(实际的用例是,我有一个未知编码的“类似文本”的数据,我只想把它直接传递给stdout,而不必对特定的编码作出承诺。)
您可以定义一个名为
_print
的本地函数(甚至可以通过将其命名为print
来重写系统print
函数),如下所示:输出应该是
AB
。你知道吗注:通常系统
print
函数会向输出中添加一个换行符。上面的_print
只输出数据(要么bytes
,要么假设它是str
),而不使用换行符。你知道吗缓冲实现
如果需要缓冲I/O,可以使用
io
库中的工具来管理它。你知道吗简单示例:
例如,如果在函数中执行所有输出写入,则可以使用
contextlib.contextmanager
创建工厂函数,允许您使用with ...
语句:请参见:
你不能用
flush
交错调用write
吗?你知道吗结果:
结果:
相关问题 更多 >
编程相关推荐