python相当于java OutputStream? [英] python equivalent of java OutputStream?

查看:44
本文介绍了python相当于java OutputStream?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

是否有与 java 的 OutputStreamPrintWriter?

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,标准输入/输出/错误流在sys中用stdinstdoutstderr表示代码> 模块.要获取读写字符串的类文件对象,请使用 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?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆