[英]Is it possible to have an alias for sys.stdout in python?
Consider this sample python code. 考虑一下此示例python代码。 It reads from stdin and writes to a file. 它从stdin读取并写入文件。
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. 假设我想修改该程序以写入stdout。 Then, I'll have to replace each instance of f.write()
with sys.stdout.write()
. 然后,我必须用sys.stdout.write()
替换f.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()
. 我想知道是否有一种方法可以将f
指定为sys.stdout
的别名,以便将f.write()
视为sys.stdout.write()
。
Names in Python are just bindings. Python中的名称只是绑定。 Therefore: 因此:
f = sys.stdout
Just binds the name f
to the object that's also bound to sys.stdout
... 只需将名称f
绑定到也绑定到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()
... 请注意,由于它们都是同一个对象,因此您此时对f
或sys.stdout
所做的任何更改都会影响这两者 。因此,请不要执行f.close()
因为您通常不希望执行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)
. 现在,您只需要执行f = sys.stdout
而不是f = open(fileName)
。 (And remove f.close()
) (并删除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: 是的,在python中,您可以为每个类/函数/方法等添加别名。只需将要使用的值分配给另一个变量:
import sys
f = sys.stdout
Now every method you call on f
will get called on sys.stdout
. 现在,您在f
上调用的每个方法都将在sys.stdout
上调用。 You can do this with whatever you like, for example also with i = sys.stdin
etc. 您可以使用自己喜欢的任何方式执行此操作,例如,也可以使用i = sys.stdin
等。
This is properly the job of a shell anyway; 无论如何,这完全是shell的工作。 just send it to standard out and redirect it to a file using >filename
when you invoke the script. 只需将其发送到标准输出,然后在调用脚本时使用>filename
将其重定向到文件。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.