Python Function to test ping

前端 未结 5 1513
既然无缘
既然无缘 2020-12-09 08:59

I\'m trying to create a function that I can call on a timed basis to check for good ping and return the result so I can update the on-screen display. I am new to python so I

5条回答
  •  遥遥无期
    2020-12-09 09:46

    Try this

    def ping(server='example.com', count=1, wait_sec=1):
        """
    
        :rtype: dict or None
        """
        cmd = "ping -c {} -W {} {}".format(count, wait_sec, server).split(' ')
        try:
            output = subprocess.check_output(cmd).decode().strip()
            lines = output.split("\n")
            total = lines[-2].split(',')[3].split()[1]
            loss = lines[-2].split(',')[2].split()[0]
            timing = lines[-1].split()[3].split('/')
            return {
                'type': 'rtt',
                'min': timing[0],
                'avg': timing[1],
                'max': timing[2],
                'mdev': timing[3],
                'total': total,
                'loss': loss,
            }
        except Exception as e:
            print(e)
            return None
    

提交回复
热议问题