2016-09-09 14 views
1

私はpythonwhoisを使っていくつかのドメインのバルクのwhoisチェックを行う小さなpythonスクリプトを書きました。エラーで終了するPythonスクリプトを停止する方法

スクリプトは、testdomains.txtからドメインを読み取り、1つずつチェックします。そして、それは、ドメインに関するいくつかの情報が

RESULTS.TXTするログこれは私のスクリプトです:

from time import sleep 
import pythonwhois 

def lookup(domain): 
    sleep(5) 
    response = pythonwhois.get_whois(domain) 
    ns = response['nameservers'] 
    return ns 


with open("testdomains.txt") as infile: 
    domainfile = open('results.txt','w') 
    for domain in infile: 
     ns = (lookup(domain)) 
     domainfile.write(domain.rstrip() + ',' + ns+'\n') 
    domainfile.close() 

ドメインが登録されていない場合やWHOISサーバが何らかの理由で返信に失敗したときに私の問題が生じます。スクリプトは次のように終了します:

Traceback (most recent call last): 
    File "test8.py", line 17, in <module> 
    ns = lookup(domain) 
    File "test8.py", line 9, in lookup 
    ns = response['nameservers'] 
TypeError: 'NoneType' object has no attribute '__getitem__' 

私の質問は、スクリプト全体が終了するのを避けるためですか?

エラーの場合は、スクリプトを次のドメインにジャンプして実行して終了しないようにします。 results.txtにエラーを記録することも間違いなく良いでしょう。

ありがとうございます!

答えて

4

try/exceptで例外処理を使用したいと考えています。

for domain in infile: 
    try: 
     ns = lookup(domain) 
    except TypeError as e: 
     # should probably use a logger here instead of print 
     print('domain not found: {}'.format(e)) 
     print('Continuing...') 
    domainfile.write(domain.rstrip() + ',' + ns+'\n') 
domainfile.close() 
0
with open("testdomains.txt") as infile: 
    domainfile = open('results.txt','w') 
    for domain in infile: 
     try: 
      ns = (lookup(domain)) 
      domainfile.write(domain.rstrip() + ',' + ns+'\n')\ 
     except TypeError: 
      pass 
    domainfile.close() 
0

は2つの方法があります:

関心のコードのスニペットを取るhere

例外処理上のドキュメントを読んで、あなたは、try内のお電話をラップ 1)のいずれかのことができますexpectionが発生していないことを確認するために脆いコードを削除します。 例:

from time import sleep 
import pythonwhois 

def lookup(domain): 
    sleep(5) 
    response = pythonwhois.get_whois(domain) 
    ns = response.get('nameservers') 
    return ns 


with open("testdomains.txt") as infile: 
    domainfile = open('results.txt','w') 
    for domain in infile: 
     ns = (lookup(domain)) 
     if ns: 
      domainfile.write(domain.rstrip() + ',' + ns+'\n') 
    domainfile.close() 

2)優雅に例外を処理し、コードを継続することができます。上記のように。

+2

= /うん.....それはクールではない。 – idjaw

+0

私の間違い。冗長コードが削除されました。 –

+4

"私の間違い" == "私は捕まった"。最初は盗作をしないでください。これまで – davidism

関連する問題