2

我是 python 的新手,目前我正在开发一个 GPS 跟踪器,它使用 Arduino Uno 与谷歌地图交互。我收到此错误,它不允许我为我的 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。提前致谢

4

1 回答 1

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定义的(各种套接字操作)。这将导致一个. 在这种情况下,您的代码中没有路径会导致分配一个打开的套接字连接,您可以完全删除该行。NameErrorconnconn.close()

如果需要调用on ,您首先需要检测它是否已设置事先将其设置为,然后仅在不再为时调用:.close()connNone.close()connNone

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()
于 2013-02-06T00:12:27.517 回答