5

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?

4 Answers 4

9

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

Sign up to request clarification or add additional context in comments.

Comments

4

Take a look at the io and StringIO modules.

Comments

2

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+'))

Comments

0

If you're interested just in abstracting away from the type of output you are using, just use the file parameter of built-in print function.

For example, you can use the following to print to standard output:

import sys
print("Hello world",file=sys.stdout)

Or use the following to print into a file instead:

output_file = open("output.txt","w")
print("Hello world",file=output_file)
# ... 
output_file.close()

Here's documentation of the built in function: https://docs.python.org/3/library/functions.html#print

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.