Tee不显示对fi的输出或写入

2024-05-08 03:26:51 发布

您现在位置:Python中文网/ 问答频道 /正文

我编写了一个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()

Tags: inpyimporttimemainlinesleepping
1条回答
网友
1楼 · 发布于 2024-05-08 03:26:51

以下是复制您的问题的一种更简单的方法:

$ 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

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

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

相关问题 更多 >