Alexey
Alexey

Reputation: 1438

Get access to existing thread python

Pretend one have a script with creating some testing Thread: test1.py

import threading
import time


class Test(threading.Thread):
    def __init__(self, name, alist):
        threading.Thread.__init__(self)
        self.alist = alist
        self.name = name

    def run(self):
        print "Starting thread " + self.name
        self.append_to_alist(self.alist)
        print "Exiting thread" + self.name

    def append_to_alist(self, alist):
        for x in range(5):
            self.alist.append(alist[-1]+1)
            time.sleep(10)


def main():
    alist = [1]
    # Create new thread
    thread = Test("Test thread", alist)
    thread.start()
    thread.join()
    print alist
main()

Now I run it python test1.py and then I want to run another script test2.py in order to modify existing Test thread which is working, something like this, test2.py:

import threading
thread = somehow_get_access_to_Test_thread()
thread.alist.append('test')

Is it possible?

Upvotes: 0

Views: 312

Answers (1)

jesper_bk
jesper_bk

Reputation: 503

To my knowledge there is no way for the threads to interact directly. Not only are they different threads, but they also run in separate Python processes.

In this case I believe the simplest solution is to have the list thread listen on a TCP port, and the other thread write to that port.

See for example this library.

Upvotes: 3

Related Questions