Python 写入缓冲区而不是文件
Python writes to a buffer instead of a file
我是 Python 的新手,但我遇到过我无法 explain/solve 的奇怪行为。
基本上,我需要将 python 脚本输出转发到文件。
示例:
while True:
print('tick')
time.sleep(5)
然后将输出重定向到文件
python test.py >> test.log 2>&1
但问题是在脚本完成之前文件是空的。
看起来它将输出写入某个缓冲区,并且仅在最后将此缓冲区发送到文件。
这对我来说是完全不能接受的,因为我有一个 运行 24/7 的脚本,在这种情况下,我永远不会得到正确的日志。我需要实时写入文件。
我知道使用
可能会修复它
with open('test.log', mode='a') as log_file:
但在这种情况下,我将无法在终端中查看结果。
除此之外,我将严格限制在脚本中指定的文件。
我想这实际上不是 Python 问题,而是更普遍的问题。
不过,是否可以像我在终端中看到的那样即时写入文件?
Looks like it writes the output to some buffer
没错。您可以使用 flush=True
禁用此功能,因此:
while True:
print('tick', flush=True)
time.sleep(5)
试试这个:
with open('log.log', 'w+') as log_file:
print('tick', file=log_file)
这样打印输出将转到文件而不是标准输出
我是 Python 的新手,但我遇到过我无法 explain/solve 的奇怪行为。 基本上,我需要将 python 脚本输出转发到文件。
示例:
while True:
print('tick')
time.sleep(5)
然后将输出重定向到文件
python test.py >> test.log 2>&1
但问题是在脚本完成之前文件是空的。 看起来它将输出写入某个缓冲区,并且仅在最后将此缓冲区发送到文件。
这对我来说是完全不能接受的,因为我有一个 运行 24/7 的脚本,在这种情况下,我永远不会得到正确的日志。我需要实时写入文件。
我知道使用
可能会修复它with open('test.log', mode='a') as log_file:
但在这种情况下,我将无法在终端中查看结果。 除此之外,我将严格限制在脚本中指定的文件。
我想这实际上不是 Python 问题,而是更普遍的问题。 不过,是否可以像我在终端中看到的那样即时写入文件?
Looks like it writes the output to some buffer
没错。您可以使用 flush=True
禁用此功能,因此:
while True:
print('tick', flush=True)
time.sleep(5)
试试这个:
with open('log.log', 'w+') as log_file:
print('tick', file=log_file)
这样打印输出将转到文件而不是标准输出