如何重写多标题的代码

2024-09-27 22:34:10 发布

您现在位置:Python中文网/ 问答频道 /正文

我想对我的代码执行多线程处理,但不知道如何启动。。。。基本上,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\u设备列表”的一部分

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

Tags: nameipgetdeviceusernamepasswordallcisco
2条回答

与我无关的那本书https://scaling-python.com为Python3.x中的多线程(以及实际上的多处理)提供了一些很好的解决方案。以下是一些多线程选项(但我主要是让感兴趣的读者阅读这本书,其中摘录了代码):

  1. 螺纹模块(示例2.1、2.2、2.3):
import threading
t = threading.Thread(target=my_func,args=(...,))
t.start()
t.join()
  1. 并发期货(示例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工人一起使用期货时,我确实遇到了一些问题——目前还不清楚这些问题是否可以解决

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

Python的Pool类带有一个简单的映射函数,该函数获取todo函数和iterable,请尝试以下操作:

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

相关问题 更多 >

    热门问题