欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

Python 长ping打印时间log保存至txt

程序员文章站 2022-04-09 21:22:03
...
import os
import sys  
import time
import subprocess

cur_path = r'C:\Users\xxx\Desktop\201_monitor' # save log.txt path
hostname = '10.2.53.201' # ip address


def pyping(ipaddress):
    cur_time = time.strftime('%Y_%m_%d-%H:%M:%S',time.localtime(time.time()))
    proc = subprocess.Popen(
        ['ping', '-n', '1', ipaddress],
        stdout=subprocess.PIPE)
    stdout, stderr = proc.communicate()
    ping_ret ='T:%s, R:%s' % (cur_time, stdout.decode("gbk").split("\n")[2])
    print(ping_ret) 
    return ping_ret
        

log_path = cur_path + "\\%s_ping_log.txt" % hostname
with open(log_path, "a") as logfile:
    while 1:        
        ret_ping = pyping(hostname)
        logfile.write(ret_ping+'\r\n')
        logfile.flush()
        time.sleep(60) # a print every a minute 

改了一下别人的,原网址在python3上有点问题

Reference