Tee不显示输出或写入文件 [英] Tee does not show output or write to file

查看:948
本文介绍了Tee不显示输出或写入文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我写了一个python脚本来监视某些网络资源的状态,如果可以的话,它是无限的.它会永久ping相同的3个节点,直到收到键盘中断为止.我尝试使用tee将程序的输出重定向到文件,但是不起作用:

I wrote a python script to monitor the statuses of some network resources, an infinite pinger if you will. It pings the same 3 nodes forever until it receives a keyboard interrupt. I tried using tee to redirect the output of the program to a file, but it does not work:

λ sudo ./pingster.py

15:43:33        node1 SUCESS | node2 SUCESS | node3 SUCESS
15:43:35        node1 SUCESS | node2 SUCESS | node3 SUCESS
15:43:36        node1 SUCESS | node2 SUCESS | node3 SUCESS
15:43:37        node1 SUCESS | node2 SUCESS | node3 SUCESS
15:43:38        node1 SUCESS | node2 SUCESS | node3 SUCESS
^CTraceback (most recent call last):
  File "./pingster.py", line 42, in <module>
    main()
  File "./pingster.py", line 39, in main
    sleep(1)
KeyboardInterrupt

λ sudo ./pingster.py | tee ping.log
# wait a few seconds
^CTraceback (most recent call last):
  File "./pingster.py", line 42, in <module>
    main()
  File "./pingster.py", line 39, in main
    sleep(1)
KeyboardInterrupt

λ file ping.log
ping.log: empty 

我在输出中使用的是 colorama ,我认为这可能是造成此问题的原因,但是我什至在导入colorama之前尝试打印一些东西,但该文件仍然为空.我在这里做什么错了?

I am using colorama for my output, I thought that perhaps could be causing the issue, but I tried printing something before I even imported colorama, and the file is still empty. What am I doing wrong here?

这是我正在使用的python文件

Here is the python file I'm using

#!/home/nate/py-env/ping/bin/python

from __future__ import print_function
from datetime import datetime
from collections import OrderedDict
from time import sleep

import ping
import colorama


def main():
    d = {
        'node1': '10.0.0.51',
        'node2': '10.0.0.50',
        'node3': '10.0.0.52',
    }
    addresses = OrderedDict(sorted(d.items(), key=lambda t: t[0]))

    colorama.init()
    while True:
        status = []
        time = datetime.now().time().strftime('%H:%M:%S')
        print(time, end='\t')
        for location, ip_address in addresses.items():
            loss, max_time, avg_time = ping.quiet_ping(ip_address, timeout=0.5)
            if loss < 50:
                status.append('{0} SUCESS'.format(location))
            else:
                status.append(
                    '{}{} FAIL{}'.format(
                        colorama.Fore.RED,
                        location,
                        colorama.Fore.RESET,
                    )
                )
        print(' | '.join(status))
        sleep(1)

if __name__ == '__main__':
    main()

推荐答案

这是重现问题的一种简单方法:

Here's a simpler way of reproducing your issue:

$ cat foo.py
from time import sleep
while True: 
  sleep(2)
  print "hello"

$ python foo.py
hello
hello    
(...)

$ python foo.py | tee log
(no output)

之所以会发生这种情况,是因为python在不是终端时会缓冲stdout.解缓冲的最简单方法是使用python -u:

This happens because python buffers stdout when it's not a terminal. The easiest way to unbuffer it is to use python -u:

$ python -u foo.py | tee log
hello
hello
(...)

您也可以将shebang设置为#!/usr/bin/python -u(不适用于env).

You can also set the shebang to #!/usr/bin/python -u (this does not work with env).

这篇关于Tee不显示输出或写入文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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