0

私は約urllib.error.URLErrorの例外について読んでいます。私はそれがpython2.xではもはや利用できないことを発見しました。そして、私はpy2とpy3互換にしたいという次のコードを持っています。これどうやってするの?py2とpy3のURLError例外を処理するPythonコードを書く方法

try: 
    if "api_key" not in app_data: 
     app_data["api_key"] = None 
    userprofile = stackexchange.Site(stackexchange.StackOverflow, app_key=app_data["api_key"]).user(userid) 
    print(bold("\n User: " + userprofile.display_name.format())) 
    print("\n\tReputations: " + userprofile.reputation.format()) 
    print_warning("\n\tBadges:") 
    print("\t\t Gold: " + str(userprofile.gold_badges)) 
    print("\t\t Silver: " + str(userprofile.silver_badges)) 
    print("\t\t Bronze: " + str(userprofile.bronze_badges)) 
    print("\t\t Total: " + str(userprofile.badge_total)) 
    print_warning("\n\tStats:") 
    total_questions = len(userprofile.questions.fetch()) 
    unaccepted_questions = len(userprofile.unaccepted_questions.fetch()) 
    accepted = total_questions - unaccepted_questions 
    rate = accepted/float(total_questions) * 100 
    print("\t\t Total Questions Asked: " + str(len(userprofile.questions.fetch()))) 
    print('\t\t  Accept rate is: %.2f%%.' % rate) 
    #check if the user have answers and questions or no. 
    if userprofile.top_answer_tags.fetch(): 
     print('\nMost experienced on %s.' % userprofile.top_answer_tags.fetch()[0].tag_name) 
    else: 
     print("You have 0 answers") 
    if userprofile.top_question_tags.fetch(): 
     print('Most curious about %s.' % userprofile.top_question_tags.fetch()[0].tag_name) 
    else: 
     print("You have 0 questions") 
except urllib.error.URLError: 
    print_fail("Please check your internet connectivity...") 
    exit(1) 
except Exception as e: 
    showerror(e) 
    if str(e) == "400 [bad_parameter]: `key` doesn't match a known application": 
     print_warning("Wrong API key... Deleting the data file...") 
     del_datafile() 
     exit(1) 
    elif str(e) in ("not enough values to unpack (expected 1, got 0)", "400 [bad_parameter]: ids"): 
     global manual 
     if manual == 1: 
      print_warning("Wrong user ID specified...") 
      helpman() 
      exit(1) 
     print_warning("Wrong user ID... Deleting the data file...") 
     del_datafile() 
     exit(1) 
+2

インストールパッケージを使用できる場合は、特にリンク先の[six](https://pythonhosted.org/six/#module-six.moves.urllib.error)を見てください。 – Kendas

答えて

1

@Kendasはコメントで示唆するようにあなたは、six LIBを使用することができます。

from six.moves import urllib 

それともURLErrorをインポートし、ImportError例外をキャッチしようとすることができます:あなたの場合は

try : 
    from urllib.error import URLError 
except ImportError: 
    from urllib2 import URLError 

を他のモジュールに同じmetodを適用する必要がある2番目のオプション(urlopenなど)を選択してください。

+0

2番目の解決策は私のためにうまくいきます。どうもありがとうございます。 –

関連する問題