这是我的代码,我按照在 python 文档中编写的方式处理异常,但有时我不知道会发生什么,但我的代码停留在这个 print "SERVER RESPONSE"
行并执行不能再继续前进,我必须强行阻止它。它甚至没有抛出任何异常。在 try:
block 中的 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
最佳答案
默认情况下,urllib2.urlopen()
会在没有超时的情况下执行请求。也许服务器根本没有响应请求?
关于Python:如何处理 urllib2 中服务器抛出的异常?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42234913/