SystemExit异常未被视为派生自BaseException

时间:2017-08-28 14:29:31

标签: python exception-handling

我目前正在尝试实现某些代码,如果失败,我想用特定的消息引发异常。 我想使用一个基本异常,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

1 个答案:

答案 0 :(得分:0)

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

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并提升SystemExit,现在两个都工作(?)。 @kevin @ sanket:谢谢你的帮助和时间

亚历山大