实时输出重定向 [英] Realtime output redirection

查看:113
本文介绍了实时输出重定向的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

当前,我正在使用以下命令将脚本重定向到日志文件:

Currently I am redirecting a script to a log file with the following command:

python /usr/home/scripts/myscript.py 2>&1 | tee /usr/home/logs/mylogfile.log

这似乎可行,但是只要有打印命令,它就不会立即写入文件.而是等待直到可以打印一组行.我想同时写入控制台和日志文件.如何使用输出重定向完成此操作.请注意,在控制台上运行脚本会在应有的时候打印所有内容.尽管在日志文件上执行tail -f并不顺利,因为它一次写入大约50行.有什么建议吗?

This seems to work but it does not write to the file as soon as there is a print command. Rather it waits until there is a group of lines that it can print. I want the console and the log file to be written to simultaneously. How can this be done with output redirection. Note that running the script on the console prints everything when it should. Though doing a tail -f on the logfile is not smooth since it writes about 50 lines at a time. Any suggestions?

推荐答案

听起来像 shell 实际上是缓冲的工作,因为您说它在非 tee 的.

It sounds like the shell is actually what's doing the buffering, since you say it outputs as expected to the console when not tee'd.

您可以在这篇文章中找到撤消外壳缓冲的潜在解决方案: https://unix.stackexchange.com/questions/25372/turn-off-buffering-in-pipe

You could look at this post for potential solutions to undo that shell buffering: https://unix.stackexchange.com/questions/25372/turn-off-buffering-in-pipe

但是我建议完全在 Python 中完成此操作,这样您就可以进行更直接的控制,而不是打印到 stdout ,请使用 logging 模块.

But I would recommend doing it entirely within Python, so you have more direct control, and instead of printing to stdout, use the logging module.

这将在多个日志记录级别方面提供额外的灵活性,可以将多个源集中添加到日志记录对象中(例如, stdout 和一个文件,并且可以随大小而旋转) d与logging.handlers.RotatingFileHandler相似),您将不受外壳外部缓冲的影响.

This would allow additional flexibility in terms of multiple logging levels, the ability to add multiple sources to the logging object centrally (i.e. stdout and a file -- and one which rotates with size if you'd like with logging.handlers.RotatingFileHandler) and you wouldn't be subject to the external buffering of the shell.

更多信息: https://docs.python.org/2/howto/logging.html

这篇关于实时输出重定向的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆