I am new at python, currently I am working on a GPS tracker with that interacts with Google maps using an Arduino Uno. I am getting this error and it is not letting me run the .py script for my tcpServer this is the whole script.
我是python的新手,目前我正在开发一款GPS跟踪器,它使用Arduino Uno与Google地图进行交互。我收到此错误,并没有让我运行我的tcpServer的.py脚本这是整个脚本。
#!/usr/bin/env python
import socket
import MySQLdb
TCP_IP = 'my machine IP'
TCP_PORT = 32000
BUFFER_SIZE = 40
# ClearDB. Deletes the entire tracking table
def ClearDB(curs,d ):
curs.execute ("""
INSERT INTO gmaptracker (lat, lon)
VALUES (0.0,0.0)""")
d.commit()
# Connect to the mySQL Database
def tServer():
try:
db = MySQLdb.connect (host = "my host",
user = "my user",
passwd = "my password",
db = "gmap" )
except MySQLdb.Error, e:
print "Error %d: %s" %(e.args[0], e.args[1])
sys.exit(1);
cursor = db.cursor()
# Start with a fresh tracking table
ClearDB(cursor,db)
# Set up listening Socket
try:
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
s.bind((TCP_IP, TCP_PORT))
print "Listening...."
s.listen(1)
conn, addr = s.accept()
print 'Accepted connection from address:', addr
except socket.error (message):
if s:
s.close()
print "Could not open socket: " + message
cursor.close()
conn.close()
db.close()
sys.exit(1)
try:
while 1:
data = conn.recv(BUFFER_SIZE)
if not data:break
str1,str2 = data.split("Long: ")
str1 = str1.split("Lat: ")[1]
latitude = float(str1)
longitude = float(str2)
cursor.execute ("""
INSERT INTO gmaptracker (lat, lon)
VALUES (%s,%s)""", (latitude,longitude))
db.commit()
except KeyboardInterrupt:
ClearDB(cursor,db);
cursor.close()
conn.close()
db.close()
if __name__ == '__main__':
tServer()
and this is the error that I am getting
这是我得到的错误
Traceback (most recent call last):
File "tcpServer.py", line 79, in <module>
tServer()
File "tcpServer.py", line 48, in tServer
except socket.error(message):
NameError: global name 'message' is not defined
If anyone can help me figure this out I would greatly appreciate it, as I said I am new at python I am also running python 2.7 if that helps. Thanks in advance
如果有人可以帮我解决这个问题,我会非常感激,因为我说我是python的新手我也在运行python 2.7如果有帮助的话。提前致谢
1 个解决方案
#1
2
You are not using the correct syntax for catching an exception. Instead, use:
您没有使用正确的语法来捕获异常。相反,使用:
except socket.error as serror:
message = serror.message
The socket.error
exception has two extra attributes, errno
and message
. Older code used to catch it like this:
socket.error异常有两个额外的属性,errno和message。用于捕获它的旧代码如下:
except socket.error, (value, message):
because in Python 2 you can treat an exception like a tuple and unpack it, but that's gone in Python 3 and should really not be used.
因为在Python 2中你可以像处理元组一样处理异常并将其解压缩,但是这在Python 3中已经消失了,并且应该不会被使用。
Moreover, the older except exceptiontype, targetvariable:
has been replaced by the except exceptiontype as targetvariable:
syntax as that is less ambiguous when you try to catch more than one exception type in the same statement.
此外,旧的除了exceptiontype,targetvariable:已被except exceptiontype替换为targetvariable:语法,因为当你尝试在同一语句中捕获多个异常类型时,这种模式不那么模糊。
When an exception is thrown, the normal flow of code is interrupted; instead the flow 'jumps' to the exception handler. Because of this jump, you have another problem in your code. In the exception handler you refer to conn.close()
, but the variable conn
is defined after the point where the socket exception will be thrown (the various socket operations). This will result in a NameError
. In this case, there is no path through your code that'll result in conn
being assigned an open socket connection, you can remove the conn.close()
line altogether.
抛出异常时,正常的代码流被中断;相反,流'跳转'到异常处理程序。由于这种跳转,您的代码中还有另一个问题。在异常处理程序中,您引用conn.close(),但变量conn是在抛出套接字异常的位置(各种套接字操作)之后定义的。这将导致NameError。在这种情况下,代码中没有路径会导致conn被分配一个打开的套接字连接,你可以完全删除conn.close()行。
If there was a need to call .close()
on conn
, you'd need to detect if it was set in the first place. Set it to None
, beforehand, then call .close()
only if conn
is no longer None
:
如果需要在conn上调用.close(),则需要检测它是否首先设置。事先将其设置为None,然后仅在conn不再为None时调用.close():
conn = None
try:
# ... do stuff ...
conn, addr = s.accept()
# ... do more stuff
except socket.error as serror:
# test if `conn` was set
if conn is not None:
conn.close()
#1
2
You are not using the correct syntax for catching an exception. Instead, use:
您没有使用正确的语法来捕获异常。相反,使用:
except socket.error as serror:
message = serror.message
The socket.error
exception has two extra attributes, errno
and message
. Older code used to catch it like this:
socket.error异常有两个额外的属性,errno和message。用于捕获它的旧代码如下:
except socket.error, (value, message):
because in Python 2 you can treat an exception like a tuple and unpack it, but that's gone in Python 3 and should really not be used.
因为在Python 2中你可以像处理元组一样处理异常并将其解压缩,但是这在Python 3中已经消失了,并且应该不会被使用。
Moreover, the older except exceptiontype, targetvariable:
has been replaced by the except exceptiontype as targetvariable:
syntax as that is less ambiguous when you try to catch more than one exception type in the same statement.
此外,旧的除了exceptiontype,targetvariable:已被except exceptiontype替换为targetvariable:语法,因为当你尝试在同一语句中捕获多个异常类型时,这种模式不那么模糊。
When an exception is thrown, the normal flow of code is interrupted; instead the flow 'jumps' to the exception handler. Because of this jump, you have another problem in your code. In the exception handler you refer to conn.close()
, but the variable conn
is defined after the point where the socket exception will be thrown (the various socket operations). This will result in a NameError
. In this case, there is no path through your code that'll result in conn
being assigned an open socket connection, you can remove the conn.close()
line altogether.
抛出异常时,正常的代码流被中断;相反,流'跳转'到异常处理程序。由于这种跳转,您的代码中还有另一个问题。在异常处理程序中,您引用conn.close(),但变量conn是在抛出套接字异常的位置(各种套接字操作)之后定义的。这将导致NameError。在这种情况下,代码中没有路径会导致conn被分配一个打开的套接字连接,你可以完全删除conn.close()行。
If there was a need to call .close()
on conn
, you'd need to detect if it was set in the first place. Set it to None
, beforehand, then call .close()
only if conn
is no longer None
:
如果需要在conn上调用.close(),则需要检测它是否首先设置。事先将其设置为None,然后仅在conn不再为None时调用.close():
conn = None
try:
# ... do stuff ...
conn, addr = s.accept()
# ... do more stuff
except socket.error as serror:
# test if `conn` was set
if conn is not None:
conn.close()