簡體   English   中英

使用多線程時如何正確處理此錯誤

[英]How to properly handle this error while using multi thread

我正在使用凝固汽油彈庫通過 GNS3 連接到 Arista vEOS。 故意放錯了 IP 只是為了看看我的代碼是如何處理錯誤的。 但是 try and except 沒有按預期工作。

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)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM