2017-01-12 91 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