2017-02-14 66 views
3

这是我的代码,我已经处理的异常被写入Python文档中,但有时我不知道会发生什么,但停留在这个print "SERVER RESPONSE"行我的代码,并且不向前继续下去了,我要强制停止它的方式。它甚至没有抛出任何异常。它在print "SERVER RESPONSE"try:块被打印在终端上之后才停下来。Python:如何处理由urllib2中的服务器抛出的异常?

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 

回答

-1

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

+0

执行'print“SERVER RESPONSE”'后,它停止工作,它暂停执行。其次,我的最后'else'就在'try'块的正下方。他们的缩进匹配。如果有什么我错过了,请告诉我。 –

+0

你怎么知道它已经暂停而不是简单地完成? –

+0

因为我刚刚发布了我整个程序的一部分。它的大,执行此功能后也做其他事情..请阅读我以前的评论,我再次编辑它。 –

0

默认urllib2.urlopen()而不执行超时的请求。也许服务器根本没有回应请求?

+0

是的,这也可能是问题......但我该如何处理这个问题? –

相关问题