【问题标题】:How do I exit program in try/except?如何在 try/except 中退出程序?
【发布时间】:2012-04-15 22:25:20
【问题描述】:

我有这个 try/except 代码:

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'

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

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

【问题讨论】:

    标签: python exception-handling


    【解决方案1】:

    使用 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 $?
    

    【讨论】:

      【解决方案2】:

      如果您在try 中使用if 语句,您将需要多个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 块。

      【讨论】:

        【解决方案3】:

        只需重新加注即可。对开发者更友好

        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 document,了解except 中的重新引发错误。

        【讨论】:

          【解决方案4】:

          使用

          sys.exit(1)
          

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

          【讨论】:

          • 出于好奇,使用quit()有什么问题吗?似乎没有人提到那个。
          • quit() 仅适用于交互式 Python shell。我不会在程序中使用它。它没有在docs.python.org/library/functions.html 上列出,我不希望它可以移植到其他 Python 实现中。
          【解决方案5】:

          您还可以将代码放入函数中并发出返回。您可以将其称为 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()
          

          【讨论】:

          • 出现异常时使用“return”的问题是在命令行上看不到任何错误代码。如果您有监控系统,它们通常会检查日志以及程序的返回代码,因此如果程序在所有情况下都返回 0,即使是错误也可能难以维护。
          • @linker 您仍然可以在返回之前打印错误消息。并非所有程序都需要为其他程序产生输出——有时,人类可读就足够了。
          • @agf 我只是在解释我发现在现实世界中最有用的东西,最好的是同时具有人类可读和一致的返回代码约定。
          • @linker 另一个常见的约定是从mainreturn exitcode,然后是sys.exit(main()) 或类似的。这样一来,您就有了一个 sys.exit,并且您的代码可以更好地分离。
          【解决方案6】:

          可能不是最佳做法,但它对我有用:

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

          关闭剂量似乎在“尝试”中不起作用。

          【讨论】:

          • 您基本上不再使用try-except 来处理异常,而是使用if-else。很好奇,如果它确实有效,它如何使它变得更好?
          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2019-06-26
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多