2016-08-16 31 views
0

を待って、私はsubprocess.Popenを使用して非同期ピングプロセスをしようと、私は私がこのケースでのPython 3.5非同期&Pingの

aList = [] 
async def sn(frm, to): 
    i = 0 
    for i in list(range(frm, to)): 
     aList.append(i) 

    cmd = "ping -n 1 " + '10.0.0.' 
    coroutines = [subprocess.Popen(cmd + str(i), stdout=subprocess.PIPE) for i in aList] 
    results = await asyncio.gather(*coroutines) 
    print(results) 

loop = asyncio.get_event_loop() 
loop.run_until_complete(sn(frm, to)) 
loop.close() 

答えて

0
class rscan(object): 

    state = {'online': [], 'offline': []} # Dictionary with list 
    ips = [] # Should be filled by function after taking range 

    # Amount of pings at the time 
    thread_count = 8 

    # Lock object to prevent race conditions 
    lock = threading.Lock() 

    # Using Windows ping command 
    def ping(self, ip): 
     answer = subprocess.call(['ping','-n','1',ip],stdout = open('1.txt','w')) 
     return answer == 0 and ip 


    def pop_queue(self): 
     ip = None 

     self.lock.acquire() # lock !!! 
     if self.ips: 
      ip = self.ips.pop() 

     self.lock.release() 

     return ip 


    def noqueue(self): 
     while True: 
      ip = self.pop_queue() 

      if not ip: 
       return None 

      result = 'online' if self.ping(ip) else 'offline' 
      self.state[result].append(ip) ### check again 


    def start(self): 
     threads = [] 

     for i in range(self.thread_count): 

      t = threading.Thread(target=self.noqueue) 
      t.start() 
      threads.append(t) 

     # Wait for all threads 

     [ t.join() for t in threads ] 

     return self.state 

    def rng(self, frm, to, ip3): 
     self.frm = frm 
     self.to = to 
     self.ip3 = ip3 
     for i in range(frm, to): 
      ip = ip3 + str(i) 
      self.ips.append(ip) 


if __name__== '__main__': 
    scant = rscan() 
    scant.thread_count = 8 

それを実装する方法を理解しようと、私はまた、発見したビットクラスを編集しました待つ&使用されるスレッドの代わりに、非同期

クレジット:http://blog.boa.nu/2012/10/python-threading-example-creating-pingerpy.html

関連する問題