如何编写处理py2和py3的URLError异常的python代码

时间:2017-08-10 11:44:49

标签: python python-2.7 python-3.x exception exception-handling

我读到了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)

1 个答案:

答案 0 :(得分:1)

你可以使用six lib,正如@Kendas在评论中建议的那样:

from six.moves import urllib

或者您可以尝试导入URLError并抓住ImportError例外:

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

如果您选择第二个选项,则必须将相同的方法应用于其他模块,例如urlopen等。