Python:从线程返回结果

时间:2015-05-17 13:00:24

标签: python multithreading

我试图多线程化我的Python应用程序。这就是我认为应用程序可以工作的方式:

  1. 用户
  2. 创建ipv4地址列表
  3. 对于每个ipv4地址,应用程序建立SSH连接并登录。这部分将受益于多线程,因为每个设备大约需要10秒钟才能完成。 ssh位全部由我的ConfDumper类处理。
  4. 在每个线程中,从网络设备获取一些数据,并应返回主线程(有设备列表)
  5. 完成所有线程后,将显示结果。
  6. 对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...
    

    当我调试代码并逐行逐行时,它似乎正在工作,但一旦线程关闭,线程的所有结果都将丢失。如何将结果返回主线程?

2 个答案:

答案 0 :(得分: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()

答案 1 :(得分:0)

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

相关问题