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()
.
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()
...
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With