Search code examples
pythonpython-2.7classobjectexit-code

Make parent script continue immediately after calling another script


I'm using Python 2.7.

class Client():

    def __init__(self, host, server_port):
        """
        This method is run when creating a new Client object
        """

        self.host = 'localhost'
        self.server_Port = 1337

        # Set up the socket connection to the server
        self.connection = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
        self.receiver = None
        self.myParser = MessageParser()

        # TODO: Finish init process with necessary code
        self.run()

    def run(self):
        self.connection.connect((self.host, self.server_Port))
        self.receiver = MessageReceiver(self, self.connection) #On this line, a MessageReceiver object is instantiated.
        self.take_input()


class MessageReceiver(Thread):

    def __init__(self, client, connection):
        super(MessageReceiver, self).__init__()

        self.myClient = client
        self.connection = connection

        self.daemon = True
        self.run()

    def run(self):
        self.myClient.receive_message(self.connection.recv(1024)) #This line blocks further progress in the code.

When the run-method in the Client object instantiates a MessageReceiver object, I want the next line of code in Client to be executed immediately, without waiting for an exit code from MessageReceiver. Is there a way to do this?


Solution

  • self.run()
    

    Call start() instead. run() executes the run method in the current thread. start() spins up another thread and calls it there.

    self.start()