39

我有这个尝试/除代码:

document = raw_input ('Your document name is ')

try:
    with open(document, 'r') as a:
        for element in a:
           print element

except:
    print document, 'does not exist'

打印“[文件名]不存在”后如何退出程序? break显然不工作,pass我不想有任何崩溃错误,所以sys.exit不是一个选择。

请忽略这try部分 - 它只是一个假人。

4

6 回答 6

44

使用 sys.exit:

import sys

try:
    # do something
except Exception, e:
    print >> sys.stderr, "does not exist"
    print >> sys.stderr, "Exception: %s" % str(e)
    sys.exit(1)

一个好的做法是打印发生的异常,以便之后进行调试。

您还可以使用traceback模块打印堆栈跟踪。

请注意,您在 sys.exit 中返回的 int 将是您程序的返回码。要查看您的程序返回的退出代码(它将为您提供有关发生的事情并且可以自动化的信息),您可以执行以下操作:

echo $?
于 2012-04-15T22:27:04.243 回答
11

使用

sys.exit(1)

不是崩溃错误,这是退出程序的一种完全正常的方式。退出代码 1 是一种约定,表示出现问题(如果运行成功,您将返回 0)。

于 2012-04-15T22:26:41.107 回答
9

只是重新提高它。对开发者更友好

document = raw_input ('Your document name is ')

try:
    with open(document, 'r') as a:
        for element in a:
           print element

except:
    print document, 'does not exist'
    raise

检查引发异常部分中关于重新引发错误的python 文档except

于 2014-10-13T07:56:09.750 回答
8

您还可以将代码放入函数中并发出返回。您可以将其称为 main ,您可以从脚本中调用它。

def main():
    document = raw_input ('Your document name is ')

    try:
        with open(document, 'r') as a:
            for element in a:
               print element

    except:
        print document, 'does not exist'
        return

if __name__ == "__main__":
    main()
于 2012-04-15T22:30:59.003 回答
5

如果您在 a 中使用if语句try,您将需要多个语句sys.exit()才能实际退出程序。

例如,您在调用某个文件的执行时正在解析参数,例如$./do_instructions.py 821

import sys

# index number 1 is used to pass a set of instructions to parse
# allowed values are integer numbers from 1 to 4, maximum number of instructions is 3
arg_vector = "821" # <- pretending to be an example of sys.argv[1]

if len(arg_vector) > 3:
    sys.exit(2) # <- this will take you out, but the following needs an extra step.

# for an invalid input (8). 
for i in arg_vector:

    # to validate that only numbers are passed as args.
    try:
        int(i) # <- 8 is valid so far
        
        # value (8) is not  valid, since is greater than 4
        if (int(i) == 0) or (int(i) > 4): 
            print("Values must be 1-4")
            # the following call does not takes you out from the program,
            # but rise the SystemExit exception.
            sys.exit(2) 
            
    except SystemExit: # <- needed to catch the previous as the first evaluation
        # The following parameter "2" is just for this example
        sys.exit(2) # <- needed to actually interrupt the execution of the program/script. 

    # if there is no "except SystemExit:", the following will be executed when the 
    # previous "if" statement evaluates to True and the sys.exit(2) is called.
    #
    # and the "print("Only num...") function will be called, even when the intention 
    # of it is to advice the *user* to use only numbers, since 8 is a number this
    # shouldn't be executed.
    except:
        print("Only numbers are allowed.")
        sys.exit(2)

否则,您希望对每个评估使用一个try-except块。

于 2020-03-25T11:30:02.107 回答
-1

可能不是最佳实践,但它对我有用:

import sys    

close = False
try:
    if SomethingBadHappend:
        close = True
except:
    pass
if close:
    sys.exit(1)

接近剂量似乎在“尝试”内不起作用。

于 2021-06-25T03:16:59.180 回答