`print()` 在某些控制台中会延迟,而 `stdout.flush` 不会延迟吗?

Does `print()` delay in some consoles where `stdout.flush` doesn't?

我正在开发一个开源 python 库,它使用 verbose_print 命令在控制台中记录输出。目前看起来像这样:

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,除了第一个参数必须是 TrueFalse.

回购所有者回复了这条消息:

I should have documented this one, but basically the issue was that in some consoles (and in the IPython notebook, at least at the time), "print" commands get delayed, while stdout.flush are instantaneous, so my method was better at providing feedback.

I would be against changing it to print unless it solves some known issues.

这仍然是一个有效的问题吗? print() 后跟 sys.stdout.flush() 会避免延迟吗?有没有更好的写法?

Source

引自文档:

print evaluates each expression in turn and writes the resulting object to standard output.

Standard output is defined as the file object named stdout in the built-in module sys. If no such object exists, or if it does not have a write() method, a RuntimeError exception is raised.

据此,print 写入 sys.stdout,所以,是的,在 printing 之后执行 sys.stdout.flush() 与 [=21= 具有相同的效果]ing 在 sys.stdout.write-ing.

之后

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

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

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