繁体   English   中英

SystemExit异常不视为源自BaseException

[英]SystemExit exception not seen as derived from BaseException

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

我搜索了一个解决方案,并找到了一个解决方案: 即使我确实定义了并将代码修改为: 我仍然收到“ TypeError:异常必须从BaseException派生”

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

但是我最终还是遇到了同样的失败……有人对我在做什么错有任何想法吗?

谢谢

亚历山大(Alexandre)

编辑:当我去定义SystemExit时,我得到了:

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

  def __init__(self, args, kwargs):
    pass

  code = None

好吧,我不知道发生了什么,但是现在可以了。 实际上,由于提取IP地址的新方法,我更改了算法,以便从文件而不是Windows命令获取IP扫描数据(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和提高SystemExit,现在两者都可以工作(?)。 @kevin @ sanket:谢谢您的帮助和时间

亚历山大(Alexandre)

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM