Python try except finally返回数据的问题

今天运行代码时,发现异常,finally中response没有定义,这个函数:

def send_to_agent(agent, data):
    send_data = '%s%s' % (json.dumps(data), '_SEND_END')
    print 'agent: %s send_data:%s ' % (agent,  send_data)
    try:
        sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
        sock.settimeout(2)
        sock.connect((agent, Conf.agent_port))                    # connect agent 
        sock.sendall(send_data)              # 发送data给agent,不去重
    except Exception as e:
        print "failed to send to agent:%s, ERROR:%s" % (str(agent), e)
        response = {'action_result': 'fail'}
    else:
        # print 'send success'
        buf = ''
        while True:
            content = sock.recv(1024)
            buf += content                  # agent封禁结果
            if buf.endswith('_SEND_END'):
                break
        buf = re.sub('_SEND_END$', '',  buf)
        response = json.loads(buf)
        #print "receive_result %s" % response
    finally:
        sock.close()
        return response

try...except...else...finally中,finally是一个独立于except和else的代码段,概念有点混淆。

正确的理解是:这个函数中,finally要使用变量,可先在try中声明定义,要返回response数据,finally中的“return response”语句移到else中,except也要加一句同样的,sock.close()语句在return数据后正常执行。

def send_to_agent(agent, data):
    send_data = '%s%s' % (json.dumps(data), '_SEND_END')
    print 'agent: %s send_data:%s ' % (agent,  send_data)
    try:
        sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
        sock.settimeout(2)
        sock.connect((agent, Conf.agent_port))                    # connect agent 
        sock.sendall(send_data)              # 发送data给agent,不去重
    except Exception as e:
        print "failed to send to agent:%s, ERROR:%s" % (str(agent), e)
        response = {'action_result': 'fail'}
        return response
    else:
        # print 'send success'
        buf = ''
        while True:
            content = sock.recv(1024)
            buf += content                  # agent封禁结果
            if buf.endswith('_SEND_END'):
                break
        buf = re.sub('_SEND_END$', '',  buf)
        response = json.loads(buf)
        return response
    finally:
        sock.close()

 

转载于:https://my.oschina.net/u/3573498/blog/1504143

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值