简体   繁体   English

Python 写入缓冲区而不是文件

[英]Python writes to a buffer instead of a file

I'm pretty new to a Python, but I've faced a weird behavior that I can't explain/solve.我对 Python 很陌生,但我遇到了一个我无法解释/解决的奇怪行为。 Basically, I need to forward python script output to a file.基本上,我需要将 python 脚本 output 转发到文件中。

Example:例子:

while True:
  print('tick')
  time.sleep(5)

then redirect output to the file然后将 output 重定向到文件

python test.py >> test.log 2>&1

But the thing is the file is empty until the script is finished.但问题是在脚本完成之前文件是空的。 Looks like it writes the output to some buffer and only at the end sends this buffer to a file.看起来它将 output 写入某个缓冲区,并且仅在最后将该缓冲区发送到文件。

This is totally unacceptable for me, as I have a script that is running 24/7 and in this case, I will never get proper logs.这对我来说是完全不能接受的,因为我有一个 24/7 运行的脚本,在这种情况下,我永远不会得到正确的日志。 I need real-time writing to a file.我需要实时写入文件。

I know it might be fixed using我知道它可能会使用

with open('test.log', mode='a') as log_file:

But in this case, I will lose the ability to view the result in the terminal.但在这种情况下,我将无法在终端中查看结果。 Besides that, I will be strictly limited to a file specified inside of a script.除此之外,我将严格限制在脚本内指定的文件。

I suppose it is not actually Python issue, but more generic.我想这实际上不是 Python 问题,而是更通用。 Still, is that possible to do instant writing to a file, just like I see it in the terminal?尽管如此,是否可以像我在终端中看到的那样即时写入文件?

Looks like it writes the output to some buffer看起来它将 output 写入某个缓冲区

That's correct.这是正确的。 You can disable this with flush=True , so:您可以使用flush=True禁用此功能,因此:

while True:
  print('tick', flush=True)
  time.sleep(5)

Try this:尝试这个:

with open('log.log', 'w+') as log_file:    
print('tick', file=log_file)

In that way the print output will go to file instead stdout这样打印 output 将 go 到文件而不是标准输出

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM