Toothpick Anemone
Toothpick Anemone

Reputation: 4636

What is an easy way to implement fprintf in python?

In python, the following will let us write to stdout:

import sys
sys.stdout.write("blah %d" % 5)

However, I want to be flexible about which stream we print to. I want to pass the stream as an argument into a function, as you would when calling fprintf in any of C derived languages. In the snippet of source code above, stdout is hard-coded into the write-statement. However, we want to be flexible about which stream we write to. we might want stderr, or some other stream instead of stdout.

Upvotes: 3

Views: 31312

Answers (3)

user2357112
user2357112

Reputation: 281642

You say

I want to pass the stream as an argument into a function

but that doesn't give you any extra flexibility. If you have a some_stream variable referring to the stream you want to write to, you can already do

some_stream.write("blah %d" % 5)

so you don't gain anything by making the stream a function argument. That said, the print function takes a file argument specifying what stream to write to:

print("blah %d" % 5, end='', file=some_stream)

Upvotes: 3

user6076171
user6076171

Reputation:

Usually, print (Python) is a replacement for printf (C) and its derivatives (fprintf, println...). Here's how the above snippet would look like in Python:

import sys

print("blah %d" % 5, file=sys.stdout)

Or:

print("blah %d" % 5)

Upvotes: 1

Toothpick Anemone
Toothpick Anemone

Reputation: 4636

The following will do:

import sys
def fprintf(stream, format_spec, *args):
    stream.write(format_spec % args)

Here is an example of a call:

fprintf(sys.stdout, "bagel %d donut %f", 6, 3.1459)

Console output:

bagel 6 donut 3.145900

Upvotes: 1

Related Questions