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

标签 python exception server urllib2 urllib

这是我的代码,我按照在 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/

相关文章:

python - 在 64 位 linux 上编译 32 位 python 模块(例如 numpy)

c++ - 编写 "anti-lack of memory"异常安全代码

java - 如何修复 java.net.SocketException : Broken pipe?

php - nginx php-fpm 无法打开流权限被拒绝

java - 在 Android 中组合来自服务器的 JSON 表

python - 仅在模板匹配(模板匹配)时才绘制正方形

python - 不使用 ":"定义函数

python - 在 Tkinter 和 PIL 中将子样本与 PhotoImage 结合使用

提交表单后出现 javax.ejb.EJBException

Java 服务器在使用 Javafx 单击按钮时停止