Tee 不显示输出或写入文件

问题描述 投票:0回答:2

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

λ 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 之前尝试打印一些内容,并且文件仍然是空的。我在这里做错了什么?

编辑:这是我正在使用的Python文件

#!/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()
python bash tee colorama
2个回答
79
投票

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

$ 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
当它不是终端时缓冲标准输出。取消缓冲的最简单方法是使用
python -u
:

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

您还可以将 shebang 设置为

#!/usr/bin/python -u
(这不适用于
env
)。


0
投票

从答案中还可以得出另一个原因。您正在执行的代码可能位于终端多路复用器内,例如

screen
tmux
。您的会话是基于伪终端的,因此
python
已缓冲
stdout

© www.soinside.com 2019 - 2024. All rights reserved.