我想对我的代码执行多线程处理,但不知道如何启动。。。。基本上,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
与我无关的那本书https://scaling-python.com为Python3.x中的多线程(以及实际上的多处理)提供了一些很好的解决方案。以下是一些多线程选项(但我主要是让感兴趣的读者阅读这本书,其中摘录了代码):
书中还有很多其他的路线。在与gunicorn/uwsgi Flask工人一起使用期货时,我确实遇到了一些问题——目前还不清楚这些问题是否可以解决
希望有帮助(如果有人有其他解决方案,也可以更新此答案)
Python的Pool类带有一个简单的映射函数,该函数获取todo函数和iterable,请尝试以下操作:
已编辑:如果要使用线程池,请使用:
相关问题 更多 >
编程相关推荐