Python - 除了 (OSError, e) - 不再在 3.3.3 中工作?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/20517785/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-18 20:39:11  来源:igfitidea点击:

Python - except (OSError, e) - No longer working in 3.3.3?

pythonexception-handlingpython-3.3

提问by Torxed

The following have worked throughout Python 3.X and is not broke in 3.3.3, can't find what's changed in the docs.

以下内容在整个 Python 3.X 中都有效,并且在 3.3.3 中没有中断,找不到文档中的更改内容。

import os

def pid_alive(pid):
    pid = int(pid)
    if pid < 0:
        return False
    try:
        os.kill(pid, 0)
    except (OSError, e):
        return e.errno == errno.EPERM
    else:
        return True

Tried different variations of the except line, for instance except OSError as e:but then errno.EPERMbreaks etc.

尝试了 except 行的不同变体,例如except OSError as e:但随后errno.EPERM中断等。

Any quick pointers?

任何快速指针?

采纳答案by Martijn Pieters

The expression except (OSError, e)neverworked in Python, not in the way you think it works. That expresion catches twotypes of exception; OSErroror whatever the global erefers to. Your code breaks when there is no global name e.

这个表达式except (OSError, e)从来没有在 Python 中起作用,也不是你认为它起作用的方式。该表达式捕获两种类型的异常;OSError或任何全局e所指的。当没有 global name 时,您的代码会中断e

The correct expression for Python 3 and Python 2.6 and newer is:

Python 3 和 Python 2.6 及更新版本的正确表达式是:

except OSError as e:

Python 2 also supports the syntax:

Python 2 还支持以下语法:

except OSError, e:

without parenthesis, or:

不带括号,或:

except (OSError, ValueError), e:

to catch more than one type. The syntax was very confusing, as you yourself discovered here.

捕捉不止一种类型。正如您自己在此处发现的那样,语法非常令人困惑。

The change was added in Python 2.6 and up, see PEP 3110 - Catching Exceptions in Python 3000and the Exception-handling changes sectionof the 2.6 What's New document.

该更改已添加到 Python 2.6 及更高版本中,请参阅PEP 3110 - 在 Python 3000 中捕获异常和2.6 新增功能文档的异常处理更改部分

As for an exception for errno.EPERM; you didn't import errno, so that is a NameErroras well.

至于例外情况errno.EPERM;你没有 import errno,所以这也是一个NameError