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

时间:2017-02-14 19:46:23

标签: python exception-handling server urllib2 urllib

这是我的代码,我已经处理了在python文档中编写的异常,但有时我不知道会发生什么,但我的代码卡在这个print "SERVER RESPONSE"行,并且不会继续任何前进,我有强行阻止它。它甚至没有抛出任何异常。在终端上打印print "SERVER RESPONSE"try:后,它才停止。

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 :(得分:0)

默认情况下plugins: [ new webpack.DefinePlugin({ 'process.env.NODE_ENV': JSON.stringify(process.env.NODE_ENV) }) ] 执行请求而不会超时。也许服务器根本没有回复请求?

答案 1 :(得分:-1)

也许它成功执行了try块,并结束了?是什么让你觉得它失败了? 另外,你的最终else:是不缩进的,这是在程序中还是只是不正确的stackoverflow格式化?