#!/usr/bin/env python import subprocessfrom threading import Threadfrom Queue import Queue num_threads = 3ips = ['127.0.0.1', '10.103.13.156','10.103.13.145']q = Queue() def pingme(i, queue): while True: ip = queue.get() print 'Thread %s pinging %s ' % (i, ip) ret = subprocess.call('ping -c 1 %s' % ip, shell=True, stdout=open('/dev/null'), stderr=subprocess.STDOUT) if ret == 0: print '%s is alive!' % ip else: print '%s is down...' % ip # start threadsfor i in xrange(num_threads): t = Thread(target=pingme, args=(i, q)) t.setDaemon(True) t.start() for ip in ips: q.put(ip) print 'main thread waiting...'q.join()print 'Done..' if __name__ == '__main__': pass
输出内容:
/usr/bin/python2.7 /home/wuguowei/Pych<strong>本文来源gao@daima#com搞(%代@#码@网2</strong>armProjects/xplan_script/test_process/my_sub_process.pyThread 1 pinging 127.0.0.1main thread waiting...Thread 0 pinging 10.103.13.156 Thread 2 pinging 10.103.13.145127.0.0.1 is alive!10.103.13.156 is alive!10.103.13.145 is alive!