Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/292.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
有没有其他方法可以中途停止Python代码而不使用sys.exit()等_Python_Exception_Exception Handling_Sys - Fatal编程技术网

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

有没有其他方法可以中途停止Python代码而不使用sys.exit()等,python,exception,exception-handling,sys,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 = 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(“我们的地球现在是一个外星世界…”)

但是,我知道有一些停止的方法,比如
quit()
exit()
sys.exit()
os.\u exit()
。问题是
sys.exit()
会停止代码,但会显示以下异常消息:

Traceback (most recent call last):
  File "C:\Users\MEERJULHASH\Documents\lazy", line 5, in <module>
    sys.exit()
SystemExit
回溯(最近一次呼叫最后一次):
文件“C:\Users\MEERJULHASH\Documents\lazy”,第5行,在
sys.exit()
系统出口
另一方面,当我尝试在最后一行代码上使用
os.\u exit()
时,出现一条错误消息,指出
TypeError:\u exit()正好接受一个参数(给定0)
<代码>退出()和
退出()
不建议用于生产代码


我的问题:是否有任何退出的命令可以阻止代码在不显示任何消息或以>>>结尾的情况下继续运行,或者它只是关闭程序?

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

您也可以尝试一种稍微安全一点的方法。我所说的方法是将主代码包装在try/except块中,捕获
SystemExit
,然后调用
os.\u exit
在那里,并且只在那里
通过这种方式,您可以在代码中的任何位置调用
sys.exit
,让它“冒泡”到顶层,优雅地关闭所有文件并运行所有清理,最后调用
os.\u 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!

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

您也可以尝试一种稍微安全一点的方法。我所说的方法是将主代码包装在try/except块中,捕获
SystemExit
,然后调用
os.\u exit
在那里,并且只在那里
通过这种方式,您可以在代码中的任何位置调用
sys.exit
,让它“冒泡”到顶层,优雅地关闭所有文件并运行所有清理,最后调用
os.\u 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!

正如@MorganThrapp所述,程序运行结束后将自动干净地退出


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

正如@MorganThrapp所述,程序运行结束后将自动干净地退出


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

简单的方法是:

  • 将所有代码封装在一个函数中,该函数通常称为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]
    
  • 在脚本的底部,执行以下操作:

    if __name__ == '__main__':
        main()
        [optionally print an exit message]
    
  • 无论您想在哪里干净地退出,只需退出主函数即可

  • 做到这一点的简单方法是:

  • 将所有代码封装在一个函数中,该函数通常称为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]
    
  • 在脚本的底部,执行以下操作:

    if __name__ == '__main__':
        main()
        [optionally print an exit message]
    
  • 无论您想在哪里干净地退出,只需退出主函数即可

  • Python将在脚本结束时自动停止。我不是说脚本结束。我是说如何中途停车。如果用户输入正确的答案,我的python代码将继续运行,但是如果答案错误,python代码应该停止。我给出的代码不是我的完整脚本…如果这是完整的程序,则在执行最后一行后,程序将自行结束:)否则,请尝试将退出代码传递给sys.exit()代码,如sys.exit(0)。这不会对我造成回溯,但我在Mac电脑上,因此可能是Windows特定的。是的,这不是我的完整代码,但我在键入sys.exit()时确实收到回溯消息,所以我会按您的方式尝试thnx;)不。这是我键入sys.exit(0)时出现的结果-顺便说一句,我已经导入了sys.Python,当它到达脚本的末尾时,它将自动停止。我不是说脚本的末尾。我是说如何中途停车。如果用户输入正确的答案,我的python代码将继续运行,但是如果答案错误,python代码应该停止。我给出的代码不是我的完整脚本…如果这是完整的程序,则在执行最后一行后,程序将自行结束:)否则,请尝试将退出代码传递给sys.exit()代码,如sys.exit(0)。这不会对我造成回溯,但我在Mac电脑上,因此可能是Windows特定的。是的,这不是我的完整代码,但我在键入sys.exit()时确实收到回溯消息,所以我会按您的方式尝试thnx;)不。这是我键入sys.exit(0)时出现的结果-顺便说一句,我已导入sys。提供的代码不是我代码的结尾。我想中途停下来。但是,我尝试了quit(),但它为用户提供了退出选项。但是,是否有任何命令可以自动退出代码而无需询问或干净地结束