gpt4 book ai didi

python - 使用多线程时如何正确处理此错误

转载 作者:行者123 更新时间:2023-12-03 07:56:20 25 4
gpt4 key购买 nike

我正在使用凝固汽油弹库通过 GNS3 连接到 Arista vEOS。我 故意输入错误的 IP 只是为了查看我的代码如何处理错误。但是尝试和异常(exception)没有按预期工作。

import napalm
import concurrent.futures

def napalm_library(ip):
driver = napalm.get_network_driver(ip[3])
optional = {"transport": "telnet"}

with driver(hostname=ip[0], username=ip[1], password=ip[2], optional_args=optional) as device:
device.load_merge_candidate("test.txt")
device.commit_config()

with concurrent.futures.ThreadPoolExecutor() as executor:
t = executor.submit(napalm_library, ['1.1.1.1','username','pass','ios'])
try:
t.result()
except TimeoutError as err1:
print(err1)
相反,它给了我这个 TimeoutError,即使我已经尝试捕捉 TimeoutError。
[WinError 10060] A connection attempt failed because the connected party did not properly respond after a period of time, or established connection failed because connected host has failed to respond
Traceback (most recent call last):
File "C:\Python38-32\lib\site-packages\pyeapi\eapilib.py", line 436, in send
self.transport.endheaders(message_body=data)
File "C:\Python38-32\lib\http\client.py", line 1225, in endheaders
self._send_output(message_body, encode_chunked=encode_chunked)
File "C:\Python38-32\lib\http\client.py", line 1004, in _send_output
self.send(msg)
File "C:\Python38-32\lib\http\client.py", line 944, in send
self.connect()
File "C:\Python38-32\lib\http\client.py", line 1392, in connect
super().connect()
File "C:\Python38-32\lib\http\client.py", line 915, in connect
self.sock = self._create_connection(
File "C:\Python38-32\lib\socket.py", line 808, in create_connection
raise err
File "C:\Python38-32\lib\socket.py", line 796, in create_connection
sock.connect(sa)
TimeoutError: [WinError 10060] A connection attempt failed because the connected party did not properly r
启发我,我应该如何处理错误。

最佳答案

当您检索线程结果时,您应该捕获错误,如下所示:

from concurrent.futures import ThreadPoolExecutor


with ThreadPoolExecutor() as executor:
t = executor.submit(napalm_library, ip_addresses)

try:
t.result()
except TimeoutError as err:
print(err)

关于python - 使用多线程时如何正确处理此错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63979684/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com