Python:如何处理urllib2中服务器抛出的异常?

3
这是我的代码,我已经按照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
2个回答

0

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


是的,那也可能是问题所在...但我该如何处理这个问题呢? - irum zahra

-1
也许它成功执行了try块并结束了?你怎么知道它失败了? 此外,你最后的else:没有缩进,这是程序中的问题还是只是不正确的stackoverflow格式?

Else语句不与try/except一起使用。要捕获所有错误,只需使用except:。 - clubby789
try:... except: ... else is not a valid format. Instead, use try:... except URLError , e: .... except: - clubby789
问题是它进入了 try: 并打印出第一行,但无法继续执行并且永远不会离开 try 块。 - irum zahra
尝试将 except URLError, e: 更改为简单的 except:;可能会发生未处理的错误。 - clubby789
抱歉,我不知道问题出在哪里。似乎没有任何可能会引起问题的东西。 - clubby789
显示剩余20条评论

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接