【问题标题】:Python: how to handle exceptions thrown by a server in urllib2?Python:如何处理 urllib2 中服务器抛出的异常?
【发布时间】:2017-07-03 06:14:24
【问题描述】:

这是我的代码,我按照 python 文档中编写的方式处理了异常,但有时我不知道会发生什么,但我的代码停留在 print "SERVER RESPONSE" 行并且不会继续前进,我必须强行停下来。它甚至没有抛出任何异常。它只是在终端上打印了 try: 中的 print "SERVER RESPONSE" 块后停止。

def upload(filename1,sampleFile,unknown_path,predictiona,predictionb):

    curr_time = (time.strftime("%H:%M:%S"))
    curr_day =  (time.strftime("%Y-%m-%d"))

    register_openers()

    datagen, headers = multipart_encode({"sampleFile": open(sampleFile), "name": filename1, "userID":'19','date': curr_day,'time': curr_time})
    print"header",headers
    request = urllib2.Request("http://videoupload.hopto.org:5000/api/Sync_log", datagen, headers)
    try:
        print "SERVER RESPONSE"
        response = urllib2.urlopen(request)
        html=response.read()

    except URLError , e:
        if hasattr(e, 'reason'):
            print 'We failed to reach a server.'
            print 'Reason: ', e.reason
        elif hasattr(e, 'code'):
            print 'The server couldn\'t fulfill the request.'
            print 'Error code: ', e.code
    else:
        print "response ",response 
        print "html ",html

【问题讨论】:

    标签: python exception-handling server urllib2 urllib


    【解决方案1】:

    默认情况下urllib2.urlopen() 执行请求时不会超时。也许服务器根本没有响应请求?

    【讨论】:

    • 是的,这也可能是问题...但是我该如何处理这个问题?
    【解决方案2】:

    也许它正在成功执行try 块,并结束?是什么让你认为它失败了? 此外,您最后的else: 没有缩进,这是在程序中还是只是stackoverflow 格式不正确?

    【讨论】:

    • 执行print "SERVER RESPONSE" 后停止工作,暂停执行。其次,我最后的else 就在try 块的正下方。他们的缩进匹配。如果有什么我想念的,请告诉我。
    • 你怎么知道它已经暂停而不是简单地完成?
    • 因为我刚刚发布了我整个程序的一部分。执行此功能后它也很大并且还在做其他事情......请阅读我之前的评论,我已经再次编辑它。
    • 是的,如果尝试块成功,它不会给我服务器响应,它应该将照片上传到服务器,作为回报,它应该打印一个响应。
    • Else 语句不与 try/except 一起使用。要捕获所有错误,只需使用 except:
    猜你喜欢
    • 2020-01-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-12-12
    • 1970-01-01
    • 2015-08-11
    • 2021-12-22
    • 2013-03-05
    相关资源
    最近更新 更多