函数未在python中定义
我试图使用scan_db()return返回的值将其传递给下一个函数json_create(response),并使用json_create(response)返回的值传递给广播字符串(Sensor_IP,jsonString) 每次我尝试运行程序时,都会出现错误“NameError:name'response'未定义”,我在任何地方都找不到有用的示例 我正在使用python 2.7函数未在python中定义,python,python-2.7,function,Python,Python 2.7,Function,我试图使用scan_db()return返回的值将其传递给下一个函数json_create(response),并使用json_create(response)返回的值传递给广播字符串(Sensor_IP,jsonString) 每次我尝试运行程序时,都会出现错误“NameError:name'response'未定义”,我在任何地方都找不到有用的示例 我正在使用python 2.7 mycursor = conn.cursor() def scan_db(): print "Sca
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)
您应该替换这段代码:
while True:
print "while loop started"
scan_db()
print "scanning db"
json_create(response)
# the rest of your code
# ...
借
解释:
您的
scan\u db()
方法将返回response
变量,您将在json\u创建(响应)
中使用该变量。您尚未存储scan\u db()
返回的结果,因此在json\u创建(响应)
中,响应
没有任何内容。尝试创建一个变量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)
同样,您也可以在while循环中执行json创建(scan\u db()),您应该
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)
也许您应该了解什么是
局部变量
?我现在得到名称错误:名称“Sensor\u IP”不是defined@moe.Patel我编辑答案,你应该得到函数json\u create
的返回,并将返回变量传递给下一个函数。但是broadcast\u string(Sensor\u IP,jsonString)
的参数Sensor\u IP
和jsonString
也没有定义…@Tangwz我不确定这些参数是否是全局变量,但我希望它们也没有定义
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)