簡體   English   中英

Python:從線程返回結果

[英]Python: return result from a thread

我正在嘗試對我的Python應用程序進行多線程處理。 這就是我認為應用程序可以工作的方式:

  1. 用戶創建的ipv4地址列表
  2. 對於每個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...

當我調試代碼並一步一步地遍歷每一行時,它似乎正在工作,但是一旦線程關閉,線程的所有結果都會丟失。 如何將結果返回主線程?

您可以使用隊列:

 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()

這比我想的要容易得多。 據我所知,您不必返回任何內容,發送給線程的對象與源相同。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM