Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it possible to have an alias for sys.stdout in python?

Tags:

python

Consider this sample python code. It reads from stdin and writes to a file.

import sys

arg1 = sys.argv[1]

f = open(arg1,'w')
f.write('<html><head><title></title></head><body>')

for line in sys.stdin:
    f.write("<p>")
    f.write(line)
    f.write("</p>")

f.write("</body></html>")
f.close() 

Suppose I want to modify this same program to write to stdout instead. Then, I'll have to replace each instance of f.write() with sys.stdout.write(). But that would be too tedious. I want to know if there is a way to specify f as an alias for sys.stdout, so that f.write() is treated as sys.stdout.write().

like image 648
CodeBlue Avatar asked Jul 23 '13 18:07

CodeBlue


1 Answers

Names in Python are just bindings. Therefore:

f = sys.stdout

Just binds the name f to the object that's also bound to sys.stdout...

Note that since they're both the same object, any changes you make to f or sys.stdout at this point will affect both... So don't do f.close() as you normally wouldn't want to do sys.stdout.close()...

like image 155
R.A.B.B.I.T Avatar answered Oct 12 '22 22:10

R.A.B.B.I.T