python equivalent of java OutputStream?

前端 未结 3 1689
轻奢々
轻奢々 2021-01-13 14:36

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 stdo

相关标签:
3条回答
  • 2021-01-13 15:24

    Take a look at the io and StringIO modules.

    0 讨论(0)
  • 2021-01-13 15:29

    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+'))
    
    0 讨论(0)
  • 2021-01-13 15:30

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

    0 讨论(0)
提交回复
热议问题