4

以下代码给出了全局名称未定义错误,但据我所见,名称定义。我是 Python 新手,这是范围问题吗?

import os, socket
from threading import Thread

class serv:
    def __init__(self):
        self.socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
        self.socket.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
        self.socket.bind(('', 443))

    def run(self):
        self.socket.listen(10)
        print "Listening"
        self.conn, self.addr = self.socket.accept()
        try:
            Thread(target=clientThread, args=(self.conn,)).start()
        except Exception, errtxt:
            print errtxt

    def exit(self):
        print "Disconnected"
        self.conn.close()

    def clientThread(conn):
        print "Connected"
        while 1:
            conn.send("Hello, worlds!\n")

S = serv()
S.run()

具体错误是

global name 'clientThread' is not defined 
4

2 回答 2

7

你应该使用

self.clientThread
于 2013-03-06T21:01:54.990 回答
1

我会做出这些改变:

(1) 传递selfself.clientThread

def run(self):
    self.socket.listen(10)
    print "Listening"
    self.conn, self.addr = self.socket.accept()
    try:
        Thread(target=self.clientThread, args=(self,)).start()
    except Exception, errtxt:
        print errtxt

(2) 参考self文献clientThread

def clientThread(self):
    print "Connected"
    while 1:
        self.conn.send("Hello, worlds!\n")

另一种可能性是让您的对象派生自threading.Thread而不是拥有一个线程。然后你的代码看起来更像这样:

import os, socket
from threading import Thread

class serv(Thread):
    def __init__(self):
        super(serv, self).__init__()
        self.socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
        self.socket.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
        self.socket.bind(('', 443))

    def run(self):
        self.socket.listen(10)
        print "Listening"
        self.conn, self.addr = self.socket.accept()
        try:
            print "Connected"
            while 1:
                self.conn.send("Hello, worlds!\n")
        except Exception, errtxt:
            print errtxt

    def exit(self):
        print "Disconnected"
        self.conn.close()

S = serv()
S.start()
于 2013-03-06T21:17:37.733 回答