如何在try/except中退出程序?

rud*_*ter 27 python exception-handling

我有这个尝试/除了代码:

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'
Run Code Online (Sandbox Code Playgroud)

打印"[filename]不存在"后如何退出程序? break并且pass显然不起作用,我不想有任何崩溃错误,因此sys.exit不是一个选项.

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

Cha*_*guy 31

使用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)
Run Code Online (Sandbox Code Playgroud)

一个好的做法是打印出现的异常,以便以后可以进行调试.

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

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

echo $?
Run Code Online (Sandbox Code Playgroud)

  • 如果有人在 10 年后阅读这篇文章,在 python 3.x 中,你可以通过以下方式打印到 stderr:`print("spam", file=sys.stderr)`。请参阅/sf/ask/390229171/ (4认同)

Gre*_*ill 10

运用

sys.exit(1)
Run Code Online (Sandbox Code Playgroud)

这不是崩溃错误,退出程序是一种非常正常的方法.退出代码1是一个约定,意味着出错(在成功运行的情况下,您将返回0).

  • `quit()`只适用于交互式Python shell.我不会在程序中使用它.它没有在http://docs.python.org/library/functions.html上列出,我不希望它可以移植到其他Python实现. (3认同)

Abh*_*jit 7

您还可以将代码放在函数中并发出返回.您可以将其称为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()
Run Code Online (Sandbox Code Playgroud)

  • @agf我只是在解释我发现在现实世界中最有用的东西,最好的是拥有人类可读和一致的返回代码约定. (2认同)

Mik*_*ike 7

如果您if在 a 中使用语句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)
Run Code Online (Sandbox Code Playgroud)

否则,您需要为每次评估使用一个try- except块。


use*_*922 5

重新加注吧.它对开发人员更友好

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
Run Code Online (Sandbox Code Playgroud)

检查蟒蛇文件中关于重新加注错误引发异常部分except.