【发布时间】:2017-08-02 19:05:20
【问题描述】:
我正在开发一个使用verbose_print 命令在控制台中记录输出的开源python 库。目前它看起来像这样:
def sys_write_flush(s):
""" Writes and flushes without delay a text in the console """
sys.stdout.write(s)
sys.stdout.flush()
def verbose_print(verbose, s):
""" Only prints s (with sys_write_flush) if verbose is True."""
if verbose:
sys_write_flush(s)
我提出了如下所示的更改:
def verbose_print(verbose, *args):
""" Prints everything passed execpt the first arguement if verbose is True."""
if verbose:
print(*args)
除了它在 Python 2 上失败(修复这个问题的奖励点!),我认为这会更好,更惯用。优点是,您可以像对待 print 一样对待 verbose_print,只是第一个参数必须是 True 或 False。
repo 所有者回复了此消息:
我应该记录这个,但基本上问题在于 一些控制台(至少在当时在 IPython 笔记本中), “打印”命令被延迟,而 stdout.flush 是瞬时的,所以 我的方法更擅长提供反馈。
除非它解决了一些已知的问题,否则我会反对将其更改为打印 问题。
这仍然是一个有效的担忧吗? print() 后跟 sys.stdout.flush() 会避免延迟吗?有没有更好的写法?
【问题讨论】: