python equivalent of java OutputStream?

六月ゝ 毕业季﹏ 提交于 2019-12-19 08:29:06

问题


Is there a Python equivalent / pseudo-equivalent to java's OutputStream or PrintWriter?

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.

How can I do this?


回答1:


"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, 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.




回答2:


Take a look at the io and StringIO modules.




回答3:


you just need an object that implements the methods that files, pipes, streams, etc... also implement. for instance, i use this class sometimes when i want to detach my python program and i want to redirect sys.stderr/sys.stdout:

class Log(object):
    """used for logging for background process"""
    def __init__(self, f):
            self.f = f
    def write(self, s):
            self.f.write(s)
            self.f.flush()
sys.stdout = sys.stderr = Log(open('/tmp/daemonlog', 'a+'))


来源:https://stackoverflow.com/questions/4512733/python-equivalent-of-java-outputstream

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!