今天運行代碼時,發現異常,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()