Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 540
Toothpick Anemone Avatar asked May 21 '26 05:05

Toothpick Anemone


1 Answers

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)
like image 109
user2357112 supports Monica Avatar answered May 23 '26 19:05

user2357112 supports Monica



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!