2014-12-17 2 views
12

필자는 파이썬 스크립트를 작성하여 일부 네트워크 자원의 상태를 모니터하고 무한한 핑거를 사용합니다. 키보드 인터럽트를 수신 할 때까지 동일한 3 개의 노드를 영원히 ping합니다. 내가 파일에 프로그램의 출력을 리디렉션 티를 사용하여 시도하지만 작동하지 않습니다 : 내 출력 colorama을 사용하고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를 가져 오기도 전에 무언가, 그리고 그 파일은 여전히 ​​비어 있습니다. 여기서 내가 뭘 잘못하고 있니?

편집 : 여기

#!/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() 
+0

pingster 쓰기 출력은 어떻게됩니까? –

+0

그냥 파이썬 바닐라 인쇄 기능을 사용하십시오 –

+0

'sudo ./pingster.py | 고양이'쇼 출력? –

답변

20

을 사용하고 파이썬 파일 다음은 문제를 재생하는 간단한 방법입니다입니다 :

$ 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 
(...) 

또한 #!/usr/bin/python -u에 오두막을 (이 env 작동하지 않습니다)을 설정할 수 있습니다.

+0

이것은 완벽하게 작동했습니다. 감사합니다! –

+2

'python' 호출을 수정할 수 없다면'PYTHONUNBUFFERED' 환경 변수를 비어 있지 않은 문자열로 설정할 수 있습니다. 이것은 같은 효과를냅니다. 'man python'은 동작을보다 자세하게 설명합니다. – dimo414

관련 문제