【问题标题】:Does `print()` delay in some consoles where `stdout.flush` doesn't?在 `stdout.flush` 没有的某些控制台中,`print()` 会延迟吗?
【发布时间】: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() 会避免延迟吗?有没有更好的写法?

Source

【问题讨论】:

    标签: python stdout flush sys


    【解决方案1】:

    引用自文档:

    print 依次计算每个表达式并写入结果 对象到标准输出。

    标准输出被定义为名为@9​​87654322@的文件对象 内置模块sys。如果不存在这样的对象,或者不存在 有一个write() 方法,会引发一个RuntimeError 异常。

    据此,print 写入sys.stdout,所以,是的,在printing 之后执行sys.stdout.flush() 与flushing 在sys.stdout.write-ing 之后的效果相同。


    print(*a) 语法在 Python 2 中失败,因为 print 不是一个函数,而是一个语句,而 fun(*stuff) 构造仅适用于函数。

    在 Python 3 中,print(*a) 将 a 包含的任何内容传递给函数 print作为单独的参数,但这等于传递一个大字符串:

    separator = ' '
    print separator.join(map(str, iterable))
    

    因此,您的代码可能如下所示:

    def verbose_print(verbose, *args):
        """ Prints everything passed except the first arguement if verbose is True."""
        if verbose:
            print " ".join(map(str, args))
            sys.stdout.flush()
    

    虽然我不明白为什么这会比原版更快或更易读。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2021-08-01
      • 1970-01-01
      • 1970-01-01
      • 2018-06-15
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-05-15
      相关资源
      最近更新 更多