如何重写多线程代码

How can I rewrite the code for multitheading

我想对我的代码进行多线程处理,但不知道如何开始....基本上 python 脚本将执行一个 "for" 循环到很多设备(在另一个文件 "pyntc_devices_list") 中定义,以备份所有设备的配置。

使用多线程,我应该运行同时备份到所有设备,而不是一个一个地备份。非常感谢您的帮助。

我的代码如下:

from pyntc import ntc_device as NTC
from pyntc_devices_list import Get_Devices_List

all_devices = Get_Devices_List()

for device in all_devices:
    print('Backing up ' + device['name'])
    try:
        DEVICE = NTC(host=device['ip'], username=device['username'], password=device['password'], device_type='cisco_ios$
        DEVICE.open()
    except Exception as unknown_error:
        print('Error: ' + str(unknown_error))
        continue

    back_config = DEVICE.backup_running_config(device['name'] + '.cfg')
    DEVICE.close()

部分"pyntc_devices_list"

ESW1 = {
    'name': 'ESW1',
    'ip': '192.168.122.72',
    'username': 'yyc',
    'password': 'cisco',
 }

 ESW2 = {
    'name': 'ESW2',
    'ip': '192.168.122.73',
    'username': 'yyc',
    'password': 'cisco',
 }

 ESW3 = {
    'name': 'ESW3',
    'ip': '192.168.122.74',
    'username': 'yyc',
    'password': 'cisco',
 }

 def Get_Devices_List():
    all_devices = [ESW1, ESW2, ESW3]
    return all_devices

Python 有 Pool class 和一个简单的 map 函数,可以获取待办事项函数和可迭代对象,请尝试以下操作:

from multiprocessing import Pool
from pyntc import ntc_device as NTC
from pyntc_devices_list import Get_Devices_List

NUM_OF_PROCESSORS = 5

all_devices = Get_Devices_List()

def backup(device):
    print('Backing up ' + device['name'])
    DEVICE = NTC(host=device['ip'], username=device['username'], password=device['password'], device_type='cisco_ios$
    DEVICE.open()
    back_config = DEVICE.backup_running_config(device['name'] + '.cfg')
    DEVICE.close()


with Pool(NUM_OF_PROCESSORS) as p:
    p.map(backup, all_devices)

编辑:如果你想要线程池使用:

from multiprocessing.pool import ThreadPool

https://scaling-python.com 这本书与我无关,它为 python 3.x 中的多线程(实际上是多处理)提供了一些很好的解决方案。下面是一些多线程的选项(不过我主要是参考感兴趣的reader看书,代码摘录就是从那本书里摘取的):

  1. 线程模块(示例 2.1、2.2、2.3):
import threading
t = threading.Thread(target=my_func,args=(...,))
t.start()
t.join()
  1. concurrent.futures(示例 2.7、2.8):
from concurrent import futures
with futures.ThreadPoolExecutor as executor:
    futures = [executor.submit(my_func) for _ in range(...)]
results = [f.result() for f in futures]

书中还有很多其他路线。我 运行 在与 gunicorn/uwsgi Flask workers 一起使用 futures 时解决了一些问题 - 目前尚不清楚这些问题是否可以解决。

希望有所帮助(如果有人有任何其他解决方案,也可以更新此答案)。