簡體   English   中英

如何編寫用於處理py2和py3的URLError異常的python代碼

[英]How do I write python code that handles URLError Exception for both py2 and py3

我讀到有關urllib.error.URLError異常的信息。 我發現它在python2.x上不再可用。 我有以下代碼,我希望使其與py2和py3兼容。 我怎樣才能做到這一點?

 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)

您可以使用six庫,如@Kendas在評論中所建議:

from six.moves import urllib

或者,您可以嘗試導入URLError並捕獲ImportError異常:

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

如果選擇第二個選項,則必須將相同的方法應用於其他模塊,例如urlopen等。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM