简体   繁体   English

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

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

I read about urllib.error.URLError exception. 我读到有关urllib.error.URLError异常的信息。 I found that it is no longer available on python2.x. 我发现它在python2.x上不再可用。 And I have the following code that I want to make it py2 and py3 compatible. 我有以下代码,我希望使其与py2和py3兼容。 How can I do this? 我怎样才能做到这一点?

 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)

You could use the six lib, as @Kendas suggests in the comments: 您可以使用six库,如@Kendas在评论中所建议:

from six.moves import urllib

Or you could try to import URLError and catch ImportError exceptions: 或者,您可以尝试导入URLError并捕获ImportError异常:

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

If you choose the second option you'll have to apply the same metod to other modules, such as urlopen , etc. 如果选择第二个选项,则必须将相同的方法应用于其他模块,例如urlopen等。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM