【问题标题】:Idiomatic use of stdout as alternative习惯性地使用标准输出作为替代
【发布时间】:2017-10-03 10:55:41
【问题描述】:

这是惯用的吗?

with open(output_file, 'w') if output_file else sys.stdout as outf:
    outf.write("hello")

with 块是否会给stdout 带来麻烦(通过关闭它)?

【问题讨论】:

  • 你为什么不试试看是否sys.stdout.closed?可以为您节省一些在这里打字的时间。
  • @MaximEgorushkin 确实,但我很忙,并认为也许有人有兴趣获得解决这个问题的积分。此外,我认为在网上有一个答案是一个很好的问题。积分交易时间 - 我没有花任何钱:)
  • 啊,我也想看看人们如何解决我遇到的问题。

标签: python stdin with-statement


【解决方案1】:

如果您在此之后尝试写入标准输出,它将:

>>> 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)

【讨论】:

  • 很好,但是仅仅因为我传递不同的参数而在两个不同的地方调用do_stuff 似乎有点奇怪。我可能会收集outf = open(output_file, 'w'),最后手动关闭文件描述符:outf.close()(如果不是标准输出)。多写一点,但只需调用do_stuff
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2019-03-16
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-02-16
相关资源
最近更新 更多