Ping a site in Python?

前端 未结 15 2258
我寻月下人不归
我寻月下人不归 2020-11-22 09:22

How do I ping a website or IP address with Python?

15条回答
  •  死守一世寂寞
    2020-11-22 09:43

    I did something similar this way, as an inspiration:

    import urllib
    import threading
    import time
    
    def pinger_urllib(host):
      """
      helper function timing the retrival of index.html 
      TODO: should there be a 1MB bogus file?
      """
      t1 = time.time()
      urllib.urlopen(host + '/index.html').read()
      return (time.time() - t1) * 1000.0
    
    
    def task(m):
      """
      the actual task
      """
      delay = float(pinger_urllib(m))
      print '%-30s %5.0f [ms]' % (m, delay)
    
    # parallelization
    tasks = []
    URLs = ['google.com', 'wikipedia.org']
    for m in URLs:
      t = threading.Thread(target=task, args=(m,))
      t.start()
      tasks.append(t)
    
    # synchronization point
    for t in tasks:
      t.join()
    

提交回复
热议问题