2017-11-30 7 views
1

私はPythonでLANホストの発見のためのスクリプトを作っています(学習経験のためにソケットライブラリを使用しようと思っています。私はホストを発見することができますが、私が持っている唯一の指標はタイムアウト応答です(pingはfloatかNoneです)。しかし、私はそれをpingすることができませんnontytpeなので、hasattrを使ってホストをチェックしようとしましたが、空の辞書があります。ホストを繰り返し処理できる優れた方法はありますか?私はホストのリストを辞書にすることができますが、それは非型による反復の問題を解決しません。どんな入力もありがとう、ありがとう。ここでNonetype属性を持つリストを反復処理する方法は? (Python)

`if __name__ == '__main__': 
live = [] 
livee = [] 
for host, ping in multi_ping_query(subnet).iteritems(): 
    subnet = host, '=', ping 
    print(subnet) 
    live.append(subnet) 
for ping in live: 
    check = hasattr(ping, 'Nonetype') 
    if check == False: 
     livee.append(host) 
print(livee) 

がmulti_ping_queryするための機能である、私はそれが私はどちらかそれで多くの成功を持っていなかったが接続できない場合、それは文字列を返すように微調整しようとしました。あなたのコードをテストすることなく

def multi_ping_query(hosts, timeout=1, step=512, ignore_errors=False): 
results, host_list, id = {}, [], 0 
for host in hosts: 
    try: 
     host_list.append(socket.gethostbyname(host)) 
    except socket.gaierror: 
     results[host] = None 
while host_list: 
    sock_list = [] 
    for ip in host_list[:step]: # select supports only a max of 512 
     id += 1 
     sock_list.append(PingQuery(ip, id, timeout)) 
     host_list.remove(ip) 
    # use timeout 
    asyncore.loop(timeout) 
    for sock in sock_list: 
     results[sock.get_host()] = sock.get_result() 
return results 

答えて

0

除外して、あなたはどんなイテラブルを反復処理することができますNoneの値を代わりに次のジェネレータで繰り返します。

>>> iterable = [1, None, 2, 3, None] 
>>> iterable_nonone = (x for x in iterable if x is not None) 
>>> for x in iterable_nonone: 
...  print(x) 
... 
1 
2 
3 
0

が、私は右のあなたを理解している場合だけでなしタイプagainsチェックする「Noneです」を使用し、一般に

if ping is not None: 
    live.append(host) 
関連する問題