【问题标题】:SystemExit exception not seen as derived from BaseExceptionSystemExit 异常未视为派生自 BaseException
【发布时间】:2018-02-05 20:48:11
【问题描述】:

我目前正在尝试实现一些代码,如果它失败了,我想引发一个带有特定消息的异常。 我想使用一个基本异常 SystemExit,它应该派生自 BaseException。我导入 sys 模块

我以这种方式提出异常:

add_ip = None
# search for the ip address associated with the equipment's mac address
for i in range(0, len(add_match)):
    found = add_match[i].find(add_mac)
    if found != -1:
        add_ip = add_match[i].split()[0]

// it turns out that I don't find the matching IP address

if add_ip is not None:
    print("@IP =\t", add_ip)  # log matching IP
else:
    raise (SystemExit, "failure retrieving interface's IP address")

当我遇到问题时,我最终会收到一个错误提示

TypeError: exceptions must derive from BaseException

我搜索了一个解决方案并找到了这个:I get "TypeError: exceptions must derive from BaseException" even though I did define it 并将我的代码修改为:

raise SystemExit("failure retrieving interface's IP address")

但我最终还是遇到了同样的失败...... 有谁知道我做错了什么?

谢谢你

亚历山大

编辑: 当我去定义 SystemExit 时,我明白了:

class SystemExit(BaseException):
  """ Request to exit from the interpreter. """

  def __init__(self, args, kwargs):
    pass

  code = None

【问题讨论】:

  • 您的第二次尝试在我的机器上运行。你能提供一个minimal reproducible example 来证明该代码引发了 TypeError 吗?
  • 您使用的是哪个版本的 Python? docs.python.org/2/library/exceptions.html#exceptions.SystemExit 表示 SystemExit 自 Python 2.5 以来就派生自 BaseException。您使用的是 Python 2.4 吗?请考虑升级。
  • 你能展示你的SystemExit类主体@A.Joly
  • 看起来你正在提升一个元组......
  • 另外,你根本不应该有构造函数,因为SystemExit是一个内置的异常类型,所以你不需要制作你自己的类版本。

标签: python exception-handling


【解决方案1】:

嗯, 我不知道发生了什么,但现在可以了。 实际上,由于一种提取 IP 地址的新方法,我更改了算法以便从文件中获取 IP 扫描数据,而不是从 Windows 命令(arp -a 对我的目的来说太有限)所以我将代码修改为如下:

add_ip = None

# parse a previousely saved Angry-IP export
try:
    with open ("current_ip_scan.txt", "r") as scan_file:
        for line in scan_file:
            line = line.upper()
            line = re.sub(r':','-', line)
            if (re.search(add_mac, line)) is not None:
                add_ip = re.findall('(([0-9]{2,3}\.){3}[0-9]{3})',line)[0][0] # to get the first element of the tuple
except FileNotFoundError:
    print("*** Angry-IP export not available - do it into 'current_ip_scan.txt' in order to find the matching IP address ***")
    raise SystemExit("failure retrieving interface's IP address")

if add_ip is not None:
    # check that the ip address is a valid IP
    if(re.match('(([0-9]{2,3}\.){3}[0-9]{3})', add_ip)) is not None:
        print("@IP =\t", add_ip)  # log matching IP
    else:
        raise SystemExit("failure retrieving interface's IP address")
else:
    #sys.exit("failure retrieving interface's IP address")
    raise SystemExit("failure retrieving interface's IP address")

return add_ip

我尝试了 sys.exti 和 raise SystemExit 两者现在都可以工作(?)。 @kevin @ sanket:感谢您的帮助和时间

亚历山大

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-05-05
    • 2021-10-31
    • 2022-10-20
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多