函数没有定义python

时间:2017-04-11 02:34:11

标签: python python-2.7 function

我正在尝试使用scan_db()返回的返回值将其传递给下一个函数json_create(response)并使用我的json_create(response)返回传递给我的broadcast_string(Sensor_IP,jsonString)。 / p>

每次我尝试运行程序时都会收到错误“NameError:name'response'未定义”我无法在任何地方找到有用的示例。

我正在使用python 2.7

mycursor = conn.cursor()


def scan_db():
    print "Scanning DB"
    mycursor.execute("SELECT * FROM outputs ORDER BY ID DESC LIMIT 1;")
    response = mycursor.fetchall()

    return response


def json_create(response):
    ID, Sensor_ID, Sensor_IP, State, Pending_Update, TimeStamp = response[0]

    print "Json string creating"
    print ""
    print "ID", ID
    print "Sensor Name", Sensor_ID
    print "Sensor IP", Sensor_IP
    print "State", State
    print "Pending update", Pending_Update
    print "Time", TimeStamp
    print ""

    jsonSwitch = {'Sensor_Name': Sensor_ID, 'Sensor_IP': Sensor_IP, 'State': State,
              'Pending_Update': Pending_Update}

    jsonString = json.dumps(jsonSwitch)

    return jsonString, Sensor_IP


def broadcast_string(Sensor_IP, jsonString):
    UDP_IP = Sensor_IP  # broadcast
    UDP_PORT = 5002

    print "UDP target IP:", UDP_IP
    print "UDP target port:", UDP_PORT
    print "message:", jsonString

    cs = socket(AF_INET, SOCK_DGRAM)
    cs.setsockopt(SOL_SOCKET, SO_REUSEADDR, 1)
    cs.setsockopt(SOL_SOCKET, SO_BROADCAST, 1)
    cs.sendto(jsonString, (UDP_IP, UDP_PORT))


while True:
   print "while loop started"
   scan_db()
   print "scanning db"
   json_create(response)
   print "creating Json string"
   broadcast_string(Sensor_IP, jsonString)
   print "broadcasting packet"
   time.sleep(2)

3 个答案:

答案 0 :(得分:0)

你应该替换这段代码:

while True:
   print "while loop started"
   scan_db()
   print "scanning db"
   json_create(response)
   # the rest of your code
   # ...

通过

while True:
   print "while loop started"
   # create a new response variable
   response = scan_db()
   print "scanning db"
   json_create(response)
   # the rest of your code
   # ....

<强>阐释:

您的scan_db()方法会返回您在response中使用的json_create(response)变量。

答案 1 :(得分:0)

您尚未存储scan_db()返回的结果,因此在json_create(response) response中没有任何内容。尝试创建变量response并将其内容设置为值scan_db(),如下所示返回:

while True:
   print "while loop started"
   response = scan_db() # edit this line
   print "scanning db"
   json_create(response)
   print "creating Json string"
   broadcast_string(Sensor_IP, jsonString)
   print "broadcasting packet"
   time.sleep(2)

同样你也可以json_create(scan_db())

答案 2 :(得分:0)

在while循环中,你应该

while True:
   print "while loop started"
   response = scan_db()
   print "scanning db"
   jsonString, Sensor_IP = json_create(response)
   print "creating Json string"
   broadcast_string(Sensor_IP, jsonString)
   print "broadcasting packet"
   time.sleep(2)

也许你应该学习什么是local variable