Search code examples
pythonbottle

Bottle Python ping check 5 pings


I am trying to write a script to print a ping check to the browser with 5 pings.

This script:

from bottle import route, run, template
import subprocess

@route('/pings/<ip>')

def ping(ip):
   param = '-c 1'
   command = ['ping', param, ip]
   num = 0
   while (num < 6):
      return subprocess.check_output(command)
      num += 1

run(host='0.0.0.0', port=8080)

Currently outputs to the browser as follows:

PING 8.8.8.8 (8.8.8.8) 56(84) bytes of data. 64 bytes from 8.8.8.8: icmp_seq=1 ttl=54 time=17.7 ms --- 8.8.8.8 ping statistics --- 1 packets transmitted, 1 received, 0% packet loss, time 0ms rtt min/avg/max/mdev = 17.756/17.756/17.756/0.000 ms

But it doesn't print out 5 pings like I expect it to. It only prints out the one ping, is it for some reason only printing out the last one? How can I print out 5 pings like it would look if you ran it from a shell command.

Thanks.


Solution

  • The loop is only running once because return is executed during the first iteration of the loop therefore you're only getting the first result. You can get the ping result and append that to a list then once the loop is complete you can just return that list.

    def ping(ip):
       param = '-c 1'
       command = ['ping', param, ip]
       num = 0
       output = []
       while (num < 6):
          output.append(subprocess.check_output(command))
          num += 1
       return output // or return "\n".join(output)