问题描述
是否存在与Java的或?
Is there a Python equivalent / pseudo-equivalent to java's OutputStream or PrintWriter?
我希望能够拥有一个代表stdout / sterr之类的流,一个文件或其他东西(管道或套接字或虚拟接收器)并将其抽象出来,所以我可以将输出发送给它。
I want to be able to have a handle that represents either a stream like stdout/sterr, or a file, or something else (a pipe or a socket or a dummy sink) and abstract away what kind of thing it is, so I can just send output to it.
我该怎么做?
推荐答案
抽象出它的类型在Python中自动发生-称为鸭式打字。只需将任何类似文件的对象传递给函数,并使其使用类似文件的对象的接口即可。
"Abstracting away what type it is" happens automatically in Python - it's called 'duck typing'. Just pass any file-like object to the function, and have it use the interface of file-like objects.
FWIW,表示标准的输入/输出/错误流在<$ c中由 stdin
, stdout
和 stderr
$ c> sys 模块。要获取可读写字符串的类文件对象,请使用 StringIO
模块。
FWIW, the standard input/output/error streams are represented by stdin
, stdout
and stderr
in the sys
module. To get file-like objects that read and write strings, use the StringIO
module.
这篇关于python等效于java OutputStream?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!