如何以自己的方式处理python生成的错误消息?

2024-04-27 12:37:36 发布

您现在位置:Python中文网/ 问答频道 /正文

对于以下代码,

    opts, args = getopt.getopt(sys.argv[1:], "c:", ...
    for o,v in opts:
...
        elif o in ("-c", "--%s" % checkString):
            kCheckOnly = True
            clientTemp = v

如果我没有在-c后面给出参数,我会得到如下的错误消息。在

^{pr2}$

有没有什么方法可以捕捉到这个错误,并处理它来打印这样的内容?似乎仅仅用try/except包装代码是行不通的。在

ERROR: You forgot to give the file name after -c option

Tags: 代码intruefor参数错误sysargs
2条回答

正确的答案是使用OptionParser模块,而不是尝试“自己动手”。在

你可以接住getopt.GetoptError并亲自检查“opt”和“msg”属性:

try:
    opts, args = getopt.getopt(sys.argv[1:], "c:", ...
except getopt.GetoptError, e:
    if e.opt == 'c' and 'requires argument' in e.msg:
        print >>sys.stderr, 'ERROR: You forgot to give the file name after -c option'
        sys.exit(-1)

相关问题 更多 >