【问题标题】:How do I write python code that handles URLError Exception for both py2 and py3如何编写处理 py2 和 py3 的 URLError 异常的 python 代码
【发布时间】:2017-08-10 11:44:49
【问题描述】:

我读到了urllib.error.URLErrorexception。我发现它在 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,特别是链接部分。

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


【解决方案1】:

您可以使用six 库,正如@Kendas 在 cmets 中所建议的那样:

from six.moves import urllib

或者您可以尝试导入URLError 并捕获ImportError 异常:

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

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

【讨论】:

  • 第二种解决方案对我来说效果很好;非常感谢。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2019-03-26
  • 1970-01-01
  • 2011-11-11
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-12-13
相关资源
最近更新 更多