我有一個小程序,通過發送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()
感謝,
什麼都沒有,因爲我不知道它應該真正去哪部分代碼,也可以使用一個轉義序列 – felix001
我是否理解你想通過'SIGINT'或類似的方式來停止程序? – bereal
什麼方法可以讓我通過來自客戶端瀏覽器的AJAX調用發送停止請求.. – felix001