赋值前引用的区域设置变量套接字



我知道还有其他帖子与我的类似,但我没有从这些帖子中得到任何有用的东西,所以我开始了。

我有这个代码,我使用:

def startElection():
  index = vesselList.index(getmyip())
  if index >= (len(vesselList)-1):
    neighbour = vesselList[0]
  else:
    neighbour = vesselList[index+1]
  try:
    socket = openconn(neighbour, destport, localip=None, localport=None, timeout = 5)
    socket.send(iD)
    socket.close()
  except socket.error, exc:
    print "Caught exception socket.error : %s" % exc

我得到错误:

Exception (with type 'exceptions.UnboundLocalError'): local variable 'socket' referenced before assignment

我已尝试更改套接字的名称。我试过在try方法之前写socket=None。我真的不知道为什么会发生这种事。

********编辑1********

我有这个代码,几乎和我第一次给你们看的代码一模一样。我下面的这段代码运行起来非常好,没有错误。当我取消注释对startElection()的函数调用时,下面的代码运行得很好。

 #Start the for loop to send the new word to all the vessels in our vesselList. 
  destport = 63166
  for destHost in vesselList:
    if destHost != getmyip(): #Obviously we wont be needing to send it to the vessel it was made in. 
      try:
        soocket = openconn(destHost, destport, localip=None, localport=None, timeout = 5)
        soocket.send(userMSG)
        soocket.close()
      except soocket.error, exc:
        print "Caught exception socket.error : %s" % exc

您将套接字用作变量名和类型。

socket.error类型在套接字类上。因为您已经声明了socket是一个变量,所以运行时可能已经创建了没有引用的本地变量名,然后尝试使用它来设置异常处理程序。

更改变量的名称,问题就会消失。

在我的情况下,端口号定义错误。一个快速的改变解决了我的问题!

最新更新