What is an easy way to implement fprintf in python?
What is an easy way to implement fprintf in python?
You say
I want to pass the stream as an argument into a function
but that doesnt 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 dont 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)
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
What is an easy way to implement fprintf in python?
Usually, print
(Python) is a replacement for printf
(C) and its derivatives (fprintf
, println
…). Heres how the above snippet would look like in Python:
import sys
print(blah %d % 5, file=sys.stdout)
Or:
print(blah %d % 5)