标准输出的惯用用法作为替代
Idiomatic use of stdout as alternative
这是惯用语吗?
with open(output_file, 'w') if output_file else sys.stdout as outf:
outf.write("hello")
with
块是否会给 stdout
带来麻烦(通过关闭它)?
如果您在此之后尝试写入标准输出,它将:
>>> import sys
>>> output_file = None
>>> with open(output_file, 'w') if output_file else sys.stdout as outf:
... outf.write("hello")
...
hello5
>>> print("test")
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
ValueError: I/O operation on closed file.
可以以某种方式安全使用它的唯一方法是作为脚本中的最后一条语句,您知道以后不会使用 stdout
,例如:
if __name__ == '__main__':
output_file = ... # parse arguments
with open(output_file, 'w') if output_file else sys.stdout as outf:
outf.write("hello")
但即使这样也感觉不对。更好:分开打开和使用文件,并明确说明:
if __name__ == '__main__':
output_file = ... # parse arguments
if output_file:
with open(output_file, 'w') as outf:
do_stuff(outf)
else:
do_stuff(sys.stdout)
这是惯用语吗?
with open(output_file, 'w') if output_file else sys.stdout as outf:
outf.write("hello")
with
块是否会给 stdout
带来麻烦(通过关闭它)?
如果您在此之后尝试写入标准输出,它将:
>>> import sys
>>> output_file = None
>>> with open(output_file, 'w') if output_file else sys.stdout as outf:
... outf.write("hello")
...
hello5
>>> print("test")
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
ValueError: I/O operation on closed file.
可以以某种方式安全使用它的唯一方法是作为脚本中的最后一条语句,您知道以后不会使用 stdout
,例如:
if __name__ == '__main__':
output_file = ... # parse arguments
with open(output_file, 'w') if output_file else sys.stdout as outf:
outf.write("hello")
但即使这样也感觉不对。更好:分开打开和使用文件,并明确说明:
if __name__ == '__main__':
output_file = ... # parse arguments
if output_file:
with open(output_file, 'w') as outf:
do_stuff(outf)
else:
do_stuff(sys.stdout)