我是python,多线程,队列和锁定的新手。我想要实现的是一次登录多个设备,检查新映像,下载映像,然后将其安装在所有设备上,在多线程进程中,必须在开始安装之前完成下载。我尝试了以下概念,但我不知道如何完成或连接/粘合它们,任何帮助将提前感激!
from threading import Thread
import Queue
import re
from LoginCli import Device_Under_test
import sys, os, string, threading
import time
# some global vars
num_threads = 25
ips_q = Queue.Queue()
out_q = Queue.Queue()
outlock = threading.Lock()
# build IP array
ips = []
for i in range(100,200):
ips.append("10.10.10."+str(i))
user = 'root'
pword = 'password'
log = 'output.log'
def login_to_device (i, q):
"""get hosts in queue"""
while True:
# get an IP item form queue
ip = q.get()
cmd = "check for image"
#login to device:this works just fine using my loginCli script
LoginCli = Device_Under_test(str(ip), user, pword)
print_cmd= LoginCli.send_exp(cmd)
with outlock:
print print_cmd
q.task_done()
def image_download (i, q):
while True:
#get an IP item form queue
ip = q.get()
cmd = "download for image"
#NOT sure if I need to login again!
LoginCli = Device_Under_test(str(ip), user, pword)
print_cmd= LoginCli.send_exp(cmd)
search = re.search(r'image download completed 100%', LoginCli)
#if is done 100% completed then start installing the image
#Once installing is completed then reboot all devices
with outlock:
print print_cmd
q.task_done()
# Not sure if I need these functions?
def image_downoad (i, q):
def image_install (i, q):
# start the thread pool
for i in range(num_threads):
worker = Thread(target=login_to_device, args=(i, ips_q))
worker.setDaemon(True)
worker.start()
for i in range(num_threads):
worker = Thread(target=image_downoad, args=(i, ips_q))
worker.setDaemon(True)
worker.start()
# fill queue
for ip in ips:
ips_q.put(ip)
# wait until worker threads are done to exit
ips_q.join()
# print result
while True:
try:
msg = out_q.get_nowait()
except Queue.Empty:
break
print msg