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

Posted

技术标签:

【中文标题】使用多线程时如何正确处理此错误【英文标题】:How to properly handle this error while using multi thread 【发布时间】:2021-01-06 19:19:56 【问题描述】:

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

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

请启发我,我应该如何处理错误。

【问题讨论】:

【参考方案1】:

当您像这样检索线程结果时,您应该捕获错误:

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)

【讨论】:

确实更改了我的代码以适合您的答案,而不是使用列表理解等。不幸的是,错误仍然存​​在。也许我没有发现正确的错误? 您可以将napalm_libraryip_addresses 添加到您的代码中吗?也试着抓住TimeoutError only 经过编辑使其更清晰。是的,起初我尝试仅捕获 TimeoutError,但无济于事。这就是让我感到困惑的原因,尽管错误清楚地说是 TimeoutError。

以上是关于使用多线程时如何正确处理此错误的主要内容,如果未能解决你的问题,请参考以下文章

Python:使用多线程修改pandas DataFrame时,Spyder会发生错误

多线程和多处理时 fprintf 的行为如何?

尝试在多线程中处理链接时出错

如何在 PyQt5 中同时读取和写入文件时正确执行多线程?

java web多线程

如何使此代码运行得更好/更快(线程或多处理)?怎么做?