Is there such thing as File name or handle to write to console?

Go To StackoverFlow.com

1

I am using myFile.write("...") often and sometimes I'd like to see the output in the console rather than re-opening the updated file. I am using IDLE.

So, I'd like to know, instead of going and replacing myFile.write() with print() everywhere, can I replace the filename (output.txt) with something like STDIO when setting the myFile variable?

myFile = open("output.txt", "w")
2012-04-04 00:23
by Heitor Chang


6

You can use the sys module...

import sys
myFile=sys.stdout
myFile.write("Hello!\n")

sys.stderr is also available.

2012-04-04 00:27
by mgilson
Exactly what I needed, thanks for the snippet too :) Will accept when it lets me - Heitor Chang 2012-04-04 00:31
No problem. Happy to help - mgilson 2012-04-04 00:32


0

Here you go: sys.stdout. Just use it like any other file handle. E.g.

print >> sys.stderr, "Hi! I'm an error!"
2012-04-04 00:27
by Peter Rowell
Or on python 3... print ("Hi! I'm an error!",file=sys.stderr)mgilson 2012-04-04 02:16
@mgilson: True, however 2.x is still prevalent in production environments. Actually I'm not overly fond of either syntax, but if forced to choose I would rather have the file being written to specified first. Tomato / tomahto - Peter Rowell 2012-04-04 04:56
You can't write to stdin. Fixed that for you. ; - Li-aung Yip 2012-04-28 22:39
@Li-aungYip: Did I really do that? Sheesh! Total brain fade. Thanks for catching/fixing it - Peter Rowell 2012-04-29 05:20
Ads