2

I have read several questions on how to use print function to write on file by redirecting standard output. I find it potentially useful for logging (where logging module is sometimes inconvenient), but I wonder if there is a way to send the output to multiple destinations. Basically suggested solutions are either:

  1. Reassign stdout with sys.stdout=f #f is something that looks like a file
  2. Use contextlib.redirect_stdout

So every time there is a print(something) in code something is redirected on f. I am looking for something like

redirect_stdout([sys.stdout,f])

that outputs every something to both file f and the usual output.

Also, what is the timing of the print output (meaning if there is a function with multiple print statements, when is the content flushed on f and stdout, and what if there is an error?)?

I did some investigation, but couldn't find a solution, so I think this is above my knowledge.

Vincenzooo
  • 2,013
  • 1
  • 19
  • 33

1 Answers1

3

In Python-3 the built-in print function already has a file keyword argument that redirects the output to a specified file. So a simple way to send the output to multiple destinations would be to use two print statements.

print(something)
print(something, file=f)

See this answer for a more in-depth discussion.