2015-05-17 69 views
0

我在尝试多线程处理我的Python应用程序。这是我怎么想的应用程序将工作:Python:返回线程结果

  1. 由用户
  2. 对于每个IPv4地址创建的IPv4地址的列表,应用程序建立在SSH连接和日志这部分将来自多线程中受益因为每个设备需要大约10秒才能完成。 ssh位全部由我的ConfDumper类处理。
  3. 在每个线程中,一部分数据从网络设备中提取并返回到主线程(其中有一个设备列表)
  4. 一旦完成所有线程,就会显示一个结果。

作为新的Python和具有多线程没有经验,我已经试过这样的事情:

import threading 
import confDumper 

class MyThread (threading.Thread): 
    device = None 

    # A device object is sent as agument 
    def __init__(self, device): 
     threading.Thread.__init__(self) 
     self.device = device 

    def run(self): 
     print "Starting scan..." 
     self.sshscan() 
     print "Exiting thread" 


    def sshscan(self): 
     s = confDumper.ConfDumper(self.device.mgmt_ip, self.device.username, self.device.password, self.device.enable_password) 
     t = s.getConf() 

     if t: 
      # We got the conf, return it to the main thread, somehow... 

看来,当我通过一个调试的代码和步骤虽然线条一个是工作,但是一旦线程关闭,线程的所有结果都将丢失。我如何将结果返回到主线程?

+1

当你事实上意味着它们是实例属性时,请不要像你的'device'那样声明类级属性。这不是Python怎么做的,如果你碰巧把它变成一个可变的东西而不是None,它将在未来咬你。 – deets

+0

请参阅http://stackoverflow.com/questions/6893968/how-to-get-the-return-value-from-a-thread-in-python –

+0

@deets请详细解释一下。我有一种错觉,但你应该怎么做? – user3305609

回答

1

你可以使用一个队列:

import Queue 
import threading 
import random 
import time 


class Worker(threading.Thread): 

    def __init__(self, queue): 
     super(Worker, self).__init__() 
     self._queue = queue 


    def run(self): 
     time.sleep(5.0 * random.random()) 
     self._queue.put(str(self)) 


queue = Queue.Queue() 
workers = [Worker(queue) for _ in xrange(10)] 

for worker in workers: 
    worker.start() 

for worker in workers: 
    worker.join() 

while queue.qsize(): 
    print queue.get() 
0

这比我想象的要容易得多。据我所见,你不必返回任何东西,发送到线程的对象与源相同。