如何捕获多个例外?

时间:2016-07-14 13:44:01

标签: python sockets python-3.x python-requests

我通常相当擅长捕捉异常但这群人让我感到困惑。这是我正在使用的代码(它使用pywinrm):

import socket
def win_Upgrade_Check(kbByOS):
    for os in kbByOS:
        print(os)
        try:
            conn = winrm.Session(os, auth=("administrator","****"))
            for kb in kbByOS[os]:
                resp = conn.run_ps("get-hotfix -id {0}".format(kb))
                output = resp.std_out.decode('utf-8')
                error = resp.std_err
                if error:
                    print("KB{} not found on {}.".format(error,os))
                else:
                    print("{} found on {}.".format(kb,os))
        except timeout as e:
            print(e)
            pass

以下是我收到的错误的当前字词呕吐:

Traceback (most recent call last):
  File "/usr/local/lib/python3.5/dist-packages/requests/packages/urllib3/connection.py", line 142, in _new_conn
(self.host, self.port), self.timeout, **extra_kw)
  File "/usr/local/lib/python3.5/dist-packages/requests/packages/urllib3/util/connection.py", line 91, in create_connection
    raise err
  File "/usr/local/lib/python3.5/dist-packages/requests/packages/urllib3/util/connection.py", line 81, in create_connection
    sock.connect(sa)
socket.timeout: timed out

Traceback (most recent call last):
  File "/usr/local/lib/python3.5/dist-packages/requests/packages/urllib3/connection.py", line 142, in _new_conn
(self.host, self.port), self.timeout, **extra_kw)
  File "/usr/local/lib/python3.5/dist-packages/requests/packages/urllib3/util/connection.py", line 91, in create_connection
    raise err
  File "/usr/local/lib/python3.5/dist-packages/requests/packages/urllib3/util/connection.py", line 81, in create_connection
    sock.connect(sa)
socket.timeout: timed out

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
  File "/usr/local/lib/python3.5/dist-packages/requests/packages/urllib3/connectionpool.py", line 578, in urlopen
    chunked=chunked)
  File "/usr/local/lib/python3.5/dist-packages/requests/packages/urllib3/connectionpool.py", line 362, in _make_request
    conn.request(method, url, **httplib_request_kw)
  File "/usr/lib/python3.5/http/client.py", line 1106, in request
    self._send_request(method, url, body, headers)
  File "/usr/lib/python3.5/http/client.py", line 1151, in _send_request
    self.endheaders(body)
  File "/usr/lib/python3.5/http/client.py", line 1102, in endheaders
    self._send_output(message_body)
  File "/usr/lib/python3.5/http/client.py", line 934, in _send_output
    self.send(msg)
  File "/usr/lib/python3.5/http/client.py", line 877, in send
    self.connect()
  File "/usr/local/lib/python3.5/dist-packages/requests/packages/urllib3/connection.py", line 167, in connect
    conn = self._new_conn()
  File "/usr/local/lib/python3.5/dist-packages/requests/packages/urllib3/connection.py", line 147, in _new_conn
    (self.host, self.timeout))
requests.packages.urllib3.exceptions.ConnectTimeoutError: (<requests.packages.urllib3.connection.HTTPConnection object at 0x7fc019afed30>, 'Connection to **** timed out. (connect timeout=30)')

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
  File "/usr/local/lib/python3.5/dist-packages/requests/adapters.py", line 403, in send
    timeout=timeout
  File "/usr/local/lib/python3.5/dist-packages/requests/packages/urllib3/connectionpool.py", line 623, in urlopen
    _stacktrace=sys.exc_info()[2])
  File "/usr/local/lib/python3.5/dist-packages/requests/packages/urllib3/util/retry.py", line 281, in increment
    raise MaxRetryError(_pool, url, error or ResponseError(cause))
requests.packages.urllib3.exceptions.MaxRetryError: HTTPConnectionPool(host='****', port=5985): Max retries exceeded with url: /wsman (Caused by ConnectTimeoutError(<requests.packages.urllib3.connection.HTTPConnection object at 0x7fc019afed30>, 'Connection to **** timed out. (connect timeout=30)'))

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
  File "bulletin_parse.py", line 258, in <module>
    win_Upgrade_Check(kbByOS)
  File "bulletin_parse.py", line 247, in win_Upgrade_Check
    resp = conn.run_ps("get-hotfix -id {0}".format(kb))
  File "/usr/local/lib/python3.5/dist-packages/winrm/__init__.py", line 54, in run_ps
    rs = self.run_cmd('powershell -encodedcommand {0}'.format(encoded_ps))
  File "/usr/local/lib/python3.5/dist-packages/winrm/__init__.py", line 41, in run_cmd
    shell_id = self.protocol.open_shell()
  File "/usr/local/lib/python3.5/dist-packages/winrm/protocol.py", line 132, in open_shell
    res = self.send_message(xmltodict.unparse(req))
  File "/usr/local/lib/python3.5/dist-packages/winrm/protocol.py", line 207, in send_message
    return self.transport.send_message(message)
  File "/usr/local/lib/python3.5/dist-packages/winrm/transport.py", line 173, in send_message
    response = self.session.send(prepared_request, timeout=self.read_timeout_sec)
  File "/usr/local/lib/python3.5/dist-packages/requests/sessions.py", line 585, in send
    r = adapter.send(request, **kwargs)
  File "/usr/local/lib/python3.5/dist-packages/requests/adapters.py", line 459, in send
    raise ConnectTimeout(e, request=request)
requests.exceptions.ConnectTimeout: HTTPConnectionPool(host='****', port=5985): Max retries exceeded with url: /wsman (Caused by ConnectTimeoutError(<requests.packages.urllib3.connection.HTTPConnection object at 0x7fc019afed30>, 'Connection to **** timed out. (connect timeout=30)'))

正如您在我当前的代码中看到的,我尝试首先捕获socket.timeout。我也尝试将它更改为除了Exception为e,认为一个捕获甚至比我现有的更好,但也失败了。我尝试编辑transport.py来为requests.exceptions.ConnectTimeout添加一个例外,但是它也没有捕获它。

由于发生了多次异常,是否需要做一些特别的事情?

2 个答案:

答案 0 :(得分:1)

您可以根据需要添加任意数量的异常:

    [Authorize("DataIntegrity")]
    [ValidateAntiForgeryToken]
    [HttpPost]
    [Route("team/edit/{schoolId:int:min(1)}/{schoolName?}")]
    public async Task<IActionResult> Edit(SchoolEditViewModel model)
    {
        model.SchoolInfo = await _schoolRepo.GetSchoolInfo(model.SchoolId, _currentSeason);

        IsModelValid(model);
        if (!ModelState.IsValid)
        {
            return View(await ApplyUnboundProperties(model));
        }

        await SaveSchool(model);

        return RedirectToAction("Live", "SchoolMain", new {schoolId = model.SchoolId, schoolName = model.SchoolInfo.SchoolName});
    }

或者如果你想捕获所有异常,因为所有异常都是try: doMyFavoriteThing() except ValueError: print "Whoops!" except timeout: print "Whoopsies!" except MaxRetryError: print "Whoopsie daisies!" 类的子类,你可以这样做:

Exception

当然,第一种方法通常被认为更好 - 您可能会使用其他格式捕获NameErrors或其他愚蠢的错误。

答案 1 :(得分:0)

回答你的第一个问题:如何捕获多个例外?

您可以简单地嵌套异常:

(来自python文档。https://docs.python.org/3/tutorial/errors.html#handling-exceptions

import sys

try:
    f = open('myfile.txt')
    s = f.readline()
    i = int(s.strip())
except OSError as err:
    print("OS error: {0}".format(err))
except ValueError:
    print("Could not convert data to an integer.")
except:
    print("Unexpected error:", sys.exc_info()[0])
    raise

首先,如果没有'myfile.txt',将抛出第一个异常。它看起来像是:IOError [Errno2] No such file or directory: 'myfile.txt'

然后,如果有这样的文件但没有内容,那么将抛出第二个异常等等。

但是,为了帮助您解决第二个socket.timeout错误未被抛出的问题,您似乎应该将异常更改为socket.timeout

类型

将代码更改为:

    except socket.timeout as e:
        print(e)

这应该可以解决你的问题。