代码之家  ›  专栏  ›  技术社区  ›  wacraby

有没有其他方法可以中途停止Python代码而不使用sys。exit()等

  •  0
  • wacraby  · 技术社区  · 10 年前

    这是我的代码:

    sleep = input("Commander, would you like to sleep now? If yes then we can take out your bed. ")
    if sleep == "yes":
        Energy = Energy + 5
        print("We have taken out your bed. The spaceship is on autopilot and you may now sleep.")
        time.sleep(4)
        print("2 weeks later...")
    else:
        Energy = Energy - 5
        print("Ok. It is all your choice. BUT you WILL lose energy. Lets carry on with the journey. You have",Energy,"energy remaining.")
        time.sleep(4)
    print("Commander, you have been extremely successful so far. Well done and keep it up!")
    time.sleep(6)
    direction = input("Oh no Sir! There is trouble ahead! Please make your decision quick. It's a matter of life and death. It is also a matter of chance! There are many asteroids ahead. You may either go forwards, backwards, left or right. Make your decision...before it's too late! ")  
    if direction == "left":
        Coins = Coins + 15
        Fuel =  Fuel - 15
        while True:
            print ("You have managed to pass the asteroids, you may now carry on. You have",Fuel,"fuel left.")
            break
            continue
    elif direction == "backwards":
        print("You have retreated and gone back to Earth. You will have to start your mission all over again.")
        time.sleep(2.5)
        print("The game will now restart.")
        time.sleep(2)
        print("Please wait...\n"*3)
        time.sleep(5)
        keep_playing = True
        while True:
             script()
    elif direction == "forwards":
        Fails = Fails + 1
        print("You have crashed and passed away. Your bravery will always be remembered even if you did fail terribly. You have failed",Fails,"times.")
        time.sleep(3)
        ans = input("Do you want to play again? ")
        if ans == "yes":
            time.sleep(3)
            script()
        else:
            print("Our Earth is now an alien world...") 
            # Program stop here...
    

    在最后一行,我希望程序停止: print("Our Earth is now an alien world...")

    然而,我知道有一些方法可以像 quit() , exit() , sys.exit() , os._exit() 问题是 sys.exit() 停止代码,但出现以下异常消息:

    Traceback (most recent call last):
      File "C:\Users\MEERJULHASH\Documents\lazy", line 5, in <module>
        sys.exit()
    SystemExit
    

    另一方面,当我尝试使用 操作系统退出() 在最后一行代码中出现一条错误消息,说明 TypeError: _exit() takes exactly 1 argument (0 given) . 退出() 和 退出() 不建议用于生产代码。

    我的问题是:是否有任何退出命令阻止您的代码继续执行而不显示任何消息或以>结尾>>或者它只是关闭了程序?

    3 回复  |  直到 10 年前
        1
  •  3
  •   Idos    10 年前

    你不需要特定的命令。只要让你的程序结束,它就会自行退出。如果您想提前停止程序,可以使用 sys.exit(0) (确保你 import sys )或 os._exit(0) ( import os )这避免了 全部的 Python关闭逻辑。

    你也可以尝试一种稍微安全的方法 SystemExit ,然后呼叫 os._exit 那里 只有在那里 !
    你可以这样打电话 sys.exit 通常在代码中的任何位置,让它“冒泡”到顶层,优雅地关闭所有文件并运行所有清理,然后最后调用 操作系统退出(_E) 。这是我所说的一个例子:

    import sys
    import os
    
    emergency_code = 777
    
    try:
        # code
        if something:
            sys.exit() # normal exit with traceback
        # more code
        if something_critical: 
            sys.exit(emergency_code)  # use only for emergencies
        # more code
    except SystemExit as e:
        if e.code != emergency_code:
            raise  # normal exit
        else:
            os._exit(emergency_code)  # you won't get an exception here!
    
        2
  •  2
  •   Foon    10 年前

    简单的方法是:

    1. 将所有代码封装在一个函数中,该函数通常称为main

      def main():
          sleep = input("Commander, would you like to sleep now? If yes then we can take out your bed. ")
          [more code snipped]
          if someConditionThatShouldMakeTheScriptEnd:
              return
          [more code if the player keeps going]
      
    2. 在脚本的底部

      if __name__ == '__main__':
          main()
          [optionally print an exit message]
      
    3. 无论你想在哪里干净利落地退出,只需返回主函数
        3
  •  1
  •   Jesse Pardue    10 年前

    正如@MorganThrapp所说,当程序完成运行时,它将自动干净地退出。

    不建议将exit()和quit()用于生产代码的原因是,它会直接终止程序。更好的做法是将代码放在try-except块中( https://wiki.python.org/moin/HandlingExceptions ). 如果在except块中满足该条件,则程序将干净地结束,如果编程为,则吐出引发的异常/错误。这是“更好”的方式。出于所有目的,quit()应该可以正常工作。