gpt4 book ai didi

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

转载 作者:太空宇宙 更新时间:2023-11-03 15:33:03 36 4
gpt4 key购买 nike

我正在开发一个开源 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 except the first argument 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 insome consoles (and in the IPython notebook, at least at the time),"print" commands get delayed, while stdout.flush are instantaneous, somy method was better at providing feedback.

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

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

Source

最佳答案

引用文档:

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

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

据此,print写入 sys.stdout ,所以,是的,做 sys.stdout.flush()之后print ing 将具有与 flush 相同的效果正在阅读 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 argument if verbose is True."""
if verbose:
print " ".join(map(str, args))
sys.stdout.flush()

尽管我不明白为什么这会比原来的更快或更易读。

关于python - `print()` 在某些控制台中是否会延迟,而 `stdout.flush` 不会延迟?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42752218/

36 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com