如何刷新打印功能的输出?

2024-06-25 07:10:00 发布

您现在位置:Python中文网/ 问答频道 /正文

如何强制Python的打印函数输出到屏幕?

这不是Disable output buffering的副本-链接的问题正在尝试无缓冲输出,而这更为一般。这个问题的主要答案对这个问题来说太强大了或者太复杂了(对这个问题来说他们不是很好的答案),这个问题可以在谷歌上被一个相对的新手找到。


Tags: 答案output屏幕链接副本disable新手buffering
3条回答

运行python -h,我看到一个命令行选项

-u : unbuffered binary stdout and stderr; also PYTHONUNBUFFERED=x see man page for details on internal buffering relating to '-u'

这是relevant doc

在Python 3上,^{}可以采用可选的flush参数

print("Hello world!", flush=True)

在Python 2上,您必须执行以下操作

import sys
sys.stdout.flush()

在调用print之后。默认情况下,^{}打印到^{}(有关file objects的详细信息,请参阅文档)。

自Python 3.3以来,您可以强制普通的print()函数刷新,而无需使用sys.stdout.flush();只需将“flush”关键字参数设置为true。来自the documentation

print(*objects, sep=' ', end='\n', file=sys.stdout, flush=False)

Print objects to the stream file, separated by sep and followed by end. sep, end and file, if present, must be given as keyword arguments.

All non-keyword arguments are converted to strings like str() does and written to the stream, separated by sep and followed by end. Both sep and end must be strings; they can also be None, which means to use the default values. If no objects are given, print() will just write end.

The file argument must be an object with a write(string) method; if it is not present or None, sys.stdout will be used. Whether output is buffered is usually determined by file, but if the flush keyword argument is true, the stream is forcibly flushed.

相关问题 更多 >