2017-01-12 128 views
0

假装一个有脚本创建一些测试主题: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() 

现在我运行它python test1.py,然后我想,以修改现有Test线程中运行另一个脚本test2.py这工作时,这样的事情,test2.py

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

这可能吗?

回答

3

据我所知,线程无法直接进行交互。它们不仅是不同的线程,还可以在单​​独的Python进程中运行。

在这种情况下,我相信最简单的解决方案是让列表线程监听TCP端口,另一个线程写入该端口。

参见例如this library