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()
...
Just do
>>> import sys
>>> f = sys.stdout
>>> f.write('abc')
abc
Now you just need to do f = sys.stdout
instead of f = open(fileName)
. (And remove f.close()
)
Also , Please consider using the following syntax for files.
with open(fileName, 'r') as f:
# Do Something
The file automatically gets closed for you this way.
Yes, in python, you can alias every class / function / method etc. Just assign the value you want to use to another variable:
import sys
f = sys.stdout
Now every method you call on f
will get called on sys.stdout
. You can do this with whatever you like, for example also with i = sys.stdin
etc.
This is properly the job of a shell anyway; just send it to standard out and redirect it to a file using >filename
when you invoke the script.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.