Python try except finally返回数据的问题

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

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的代码段,概念有点混淆。json

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

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()
相关文章
相关标签/搜索