【问题标题】:Handle no internet with urllib.request [closed]使用 urllib.request 处理没有互联网 [关闭]
【发布时间】:2018-11-03 07:42:53
【问题描述】:

我有一个程序使用 urllib.request 处理 JSON API 请求,该程序在互联网断开连接时崩溃 ,我希望它继续尝试,所以当 互联网恢复时,它会继续执行请求


def data_parser(currency,coin):
    req = urllib.request.Request(url)
    r=urllib.request.urlopen(req).read()
    cont = json.loads(r.decode('utf-8'))
    kota = float(cont['prices'][currency][coin])
    pprint(cont['prices'][currency][coin])
    return kota

def main():
    period = 10
    par_1 = sys.argv[1]
    par_2 = sys.argv[2]
    while True:
        print("----")
        price_1=data_parser(par_1,par_2)
        if price_1 > 5.00:
            winsound.Beep(f,d);
        time.sleep(period)

【问题讨论】:

  • 我不希望程序在互联网断开时崩溃
  • 我的问题是如何处理这种特殊情况?

标签: python json urllib


【解决方案1】:

尝试使用try-except 块。

例如:

def data_parser(currency,coin):
    try:
        req = urllib.request.Request(url)
        r=urllib.request.urlopen(req).read()
        cont = json.loads(r.decode('utf-8'))
        kota = float(cont['prices'][currency][coin])
        pprint(cont['prices'][currency][coin])
        return kota
    except Exception as err:                   
        return data_parser(currency,coin)

【讨论】:

  • 感谢它的工作
  • 不客气 :)
猜你喜欢
  • 1970-01-01
  • 2021-10-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-01-26
  • 1970-01-01
  • 2015-03-01
相关资源
最近更新 更多