Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python threading giving global name not defined error

The following code is giving a global name not defined error, but as far as I can see the name is defined. I'm new to Python, is this a scope issue?

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

The specific error is

global name 'clientThread' is not defined 
like image 641
Philip Strong Avatar asked Feb 18 '23 07:02

Philip Strong


2 Answers

you should use

self.clientThread
like image 174
zzk Avatar answered Feb 19 '23 21:02

zzk


I would make these changes:

(1) Pass self to self.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) Reference self in clientThread

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

Another possibility is to have your object derive from threading.Thread instead of have a Thread. Then your code looks more like this:

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()
like image 31
hughdbrown Avatar answered Feb 19 '23 19:02

hughdbrown