繁体   English   中英

如何让我的 python 脚本连续将 output 的数据打印到行限制文本文件而不是标准终端?

[英]How do I get my python script that continuously prints out data to output to a line limited text file instead of the standard terminal?

在删除最旧的数据之前,我只需要允许文件包含 5000 行数据,因为 python 脚本输出新数据(类似于“bash 中的tail 命令”)。 我希望能够通过查看脚本输出到的文本文件来观察生成的数据。 我需要它能够在不需要终端的情况下在后台运行,或者在这种情况下 ssh session 处于活动状态。 在输出所有数据的 python 脚本的开头,我尝试了以下内容:

import sys
sys.stdout = open(tail -c 1G > 'output.txt', 'w', buffering=1)

但无济于事。 I am not opposed to having a bash script handle the python file, but I would prefer to simply run the python script and have it's output directed to a separate file as mentioned above if possible.

您正在描述一个循环缓冲区,它不是可以由文件支持的数据结构。 文件可以被写入(覆盖一些现有内容)或附加到,但不可能在文件中更早地移动字节。 看起来像这样做的命令通常会写入临时文件,然后将内容复制回原始文件。

正如@Luv 建议的那样,“将最后n行数据保存到磁盘”的典型方法是在几个文件之间旋转 您可以在 Python (他们使用RotatingFileHandler的建议似乎合理)或Bash中执行此操作,例如使用rotatelogs

暂无
暂无

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

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