2

私はpythonが初めてで、現在、Arduino Unoを使用してGoogleマップとやり取りするGPSトラッカーに取り組んでいます。このエラーが発生し、tcpServer の .py スクリプトを実行できません。これはスクリプト全体です。

#!/usr/bin/env パイソン

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

誰かが私がこれを理解するのを手伝ってくれるなら、私はそれを大いに感謝します. 前もって感謝します

4

1 に答える 1

2

例外をキャッチするための正しい構文を使用していません。代わりに、次を使用します。

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

例外には、2 つのsocket.error追加の属性errnomessage. 古いコードでは、次のようにキャッチしていました。

except socket.error, (value, message):

Python 2 では、例外をタプルのように扱ってアンパックできますが、Python 3 ではそれがなくなり、実際には使用しないでください。

さらに、同じステートメントで複数の例外タイプをキャッチしようとする場合にあいまいさが少なくなるため、古い構文は構文except exceptiontype, targetvariable:に置き換えられました。except exceptiontype as targetvariable:

例外がスローされると、コードの通常の流れが中断されます。代わりに、フローは例外ハンドラに「ジャンプ」します。このジャンプのために、コードに別の問題があります。を参照する例外ハンドラーではconn.close()、変数はソケット例外がスローされるポイントのconnに定義されます (さまざまなソケット操作)。これにより、. この場合、開いているソケット接続が割り当てられるコード内のパスはありません。行を完全に削除できます。NameErrorconnconn.close()

を呼び出す必要ある場合は、最初に設定.close()connれているかどうかを検出する必要があります。事前にに設定し、がなくなった場合にのみNone呼び出します。.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 に答える