有没有其他方法可以在不使用sys.exit()等的情况下中途停止Python代码

时间:2016-01-19 17:46:21

标签: python exception exception-handling sys

这是我的代码:

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

另一方面,当我尝试在最后一行代码中使用os._exit()时,会出现一条错误消息,指出TypeError: _exit() takes exactly 1 argument (0 given)。不建议将exit()quit()用于生产代码。

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

3 个答案:

答案 0 :(得分:3)

您不需要特定的命令。只是让你的程序达到目的,它将自行退出。如果您想提前停止计划,可以使用sys.exit(0)(确保import sys)或os._exit(0)import os),这样可以避免所有 Python关闭逻辑。

你也可以尝试一种更安全的imo方式。我正在谈论的方式是将主代码包装在try / except块中,捕获SystemExit,然后在那里调用os._exit只在那里! 通过这种方式,您可以在代码中的任何位置正常调用sys.exit,让它“冒泡”到顶层,优雅地关闭所有文件并运行所有清理,然后最终调用os._exit。这是我所说的一个例子:

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!

答案 1 :(得分:2)

这样做的简单方法是:

  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. 您想要彻底退出的任何地方,只需退回主要功能

答案 2 :(得分:1)

正如@MorganThrapp所说,程序在完成运行后会自动退出。

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