2013-11-09 85 views
0

我有一個小程序,通過發送10個ping來同時ping多個IP。這既在dict中記錄結果,也將狀態打印到頁面。打破Python內的螺紋循環

但是,我想允許程序不斷地ping,並讓用戶停下來,而不是依靠最大ping計數。

import os 
import re 
import time 
import sys 
import subprocess 
import Queue 
import threading 

class pinger: 

    def __init__(self,hosts): 
     self.q = Queue.Queue() 
     self.all_results = [] 
     self.hosts = hosts 

    def send_ping(self,q,ip): 
     self.q.put(self.record_results(ip)) 

    def record_results(self,ip): 
     ping_count = 0 

     host_results = { 
      "host" : ip, 
      "device" : None, 
      "sent_count" : 0, 
      "success_count": 0, 
      "fail_count": 0, 
      "failed_perc": 0, 
      "curr_status": None 
     } 

     while ping_count < 10: 
      rc = subprocess.call(['ping', '-c', '1', '-W', '1', ip], stdout=open('/dev/null', 'w'), stderr=open('/dev/null', 'w')) 
      ping_count += 1 

      # update stats 

      host = host_results['host'] 
      sent_count = host_results['sent_count'] 
      success_count = host_results['success_count'] 
      fail_count = host_results['fail_count'] 
      failed_perc = host_results['failed_perc'] 
      curr_status = host_results['curr_status'] 

      sent_count += 1 

      if rc == 0: 
       success_count += 1 
       curr_status = "Successful Response" 
      else: 
       fail_count += 1 
       curr_status = "Request Timed Out" 

      failed_perc = (fail_count/sent_count) * 100 

      host_results.update({'failed_perc': failed_perc, 'fail_count': fail_count, 'success_count': success_count, 'curr_status': curr_status, 'sent_count': sent_count}) 
      time.sleep(0.5) 
      print host_results 
     self.all_results.append(host_results) 
     return True 

    def go(self): 
     for i in self.hosts: 
      t = threading.Thread(target=self.send_ping, args = (self.q,i)) 
      t.daemon = True 
      t.start() 

感謝,

+0

什麼都沒有,因爲我不知道它應該真正去哪部分代碼,也可以使用一個轉義序列 – felix001

+0

我是否理解你想通過'SIGINT'或類似的方式來停止程序? – bereal

+0

什麼方法可以讓我通過來自客戶端瀏覽器的AJAX調用發送停止請求.. – felix001

回答

1

你可以改變while ping_count < 10條件while self.should_ping:(變量將被初始化爲True)。此外,如果您有一個主循環需要等待收集所有結果,則可以將其包裝爲​​,並在異常處理程序中將pinger.should_ping設置爲False

否則,您可以註冊爲SIGINT信號,如@bereal所述,並將should_ping變量設置爲False

+0

'SIGINT'在主線程中默認轉換爲'KeyboardInterrupt',所以這也是一樣的。 – bereal

+0

謝謝,因爲這將稍後與AJAX合併,以便客戶可以停止該過程,還有什麼我應該知道的? – felix001

+0

@bereal,是的,但如果沒有明確的地方可以放置'KeyboardException'處理程序,信號處理程序看起來更合適 –