NameError:未定义全局名称“message”

时间:2013-02-06 00:10:37

标签: python mysql python-2.7 gps gprs

我是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()

这是我得到的错误

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

如果有人能帮我解决这个问题,我会非常感激,因为我说我是python的新手我也在运行python 2.7如果有帮助的话。提前致谢

1 个答案:

答案 0 :(得分:2)

您没有使用正确的语法来捕获异常。相反,使用:

except socket.error as serror:
    message = serror.message

socket.error例外有两个额外的属性,errnomessage。用于捕获它的旧代码如下:

except socket.error, (value, message):

因为在Python 2中你可以像处理元组一样处理异常并解压缩它,但是在Python 3中它已经消失了,应该不会被使用。

此外,较旧的except exceptiontype, targetvariable:已被except exceptiontype as targetvariable:语法取代,因为当您尝试在同一语句中捕获多个异常类型时,这种语法不那么模糊。

抛出异常时,正常的代码流被中断;相反,流'跳转'到异常处理程序。由于这种跳转,您的代码中还有另一个问题。在异常处理程序中,您引用conn.close(),但变量conn在引发套接字异常的位置(各种套接字操作)之后定义。这将导致NameError。在这种情况下,代码中的无路径会导致conn被分配一个开放套接字连接,您可以完全删除conn.close()行。

如果 需要在.close()上调用conn,则需要先检测它是否已设置。事先将其设置为None,然后仅在.close()不再conn时调用None

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()