Printing to a file and a terminal at the same time

MRAB python at mrabarnett.plus.com
Tue Oct 10 19:27:10 EDT 2017


On 2017-10-10 17:00, Vail, Rick wrote:
> I have a script for Cisco devices that will do configuration or any CLI command.  What I would like to do is print the output to my terminal(windows) and to a file. I can come up with stdout parameters
> To print to a file but not to the screen and when I remove the stdout part it prints to the screen only.
> 
> This prints to a file
> filename  = open("outputfile",'w')
> sys.stdout = filename
> print ("Anything printed will go to the output file")
> 
> Remove the above and it prints to the terminal, help
> 
Why not define a function that does both?

def my_print(*args, **kwargs):
     print(*args, **kwargs)
     print(*args, **kwargs, file=output_file)



More information about the Python-list mailing list