您好,登錄后才能下訂單哦!
python中使用subprocess來使用shell
關(guān)于threading的用法
from __future__ import print_function import subprocess import threading def is_reachable(ip): if subprocess.call(["ping", "-c", "2", ip])==0:#只發(fā)送兩個(gè)ECHO_REQUEST包 print("{0} is alive.".format(ip)) else: print("{0} is unalive".format(ip)) if __name__ == "__main__": ips = ["www.baidu.com","192.168.0.1"] threads = [] for ip in ips: thr = threading.Thread(target=is_reachable, args=(ip,))#參數(shù)必須為tuple形式 thr.start()#啟動(dòng) threads.append(thr) for thr in threads: thr.join()
改良 :使用Queue來優(yōu)化(FIFO)
from __future__ import print_function import subprocess import threading from Queue import Queue from Queue import Empty def call_ping(ip): if subprocess.call(["ping", "-c", "2", ip])==0: print("{0} is reachable".format(ip)) else: print("{0} is unreachable".format(ip)) def is_reachable(q): try: while True: ip = q.get_nowait()#當(dāng)隊(duì)列為空,不等待 call_ping(ip) except Empty: pass def main(): q = Queue() args = ["www.baidu.com", "www.sohu.com", "192.168.0.1"] for arg in args: q.put(arg) threads = [] for i in range(10): thr = threading.Thread(target=is_reachable, args=(q,)) thr.start() threads.append(thr) for thr in threads: thr.join() if __name__ == "__main__": main()
以上這篇對(duì)python判斷ip是否可達(dá)的實(shí)例詳解就是小編分享給大家的全部內(nèi)容了,希望能給大家一個(gè)參考,也希望大家多多支持億速云。
免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點(diǎn)不代表本網(wǎng)站立場(chǎng),如果涉及侵權(quán)請(qǐng)聯(lián)系站長郵箱:is@yisu.com進(jìn)行舉報(bào),并提供相關(guān)證據(jù),一經(jīng)查實(shí),將立刻刪除涉嫌侵權(quán)內(nèi)容。