有没有其他方法可以在不使用 sys.exit() 等的情况下中途停止 Python 代码
Is there any other way to stop a Python code mid-way without using sys.exit() etc
这是我的代码:
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()
不推荐用于生产代码。
我的问题:是否有任何退出命令可以阻止您的代码继续运行而不显示任何消息或以 >>> 结尾,或者它只是关闭程序?
您不需要特定的命令。只要让你的程序走到尽头,它就会自行退出。如果你想过早地停止你的程序,你可以使用 sys.exit(0)
(确保你 import sys
)或 os._exit(0)
(import os
)来避免 all Python 关闭逻辑。
我也可以试试稍微安全一点的方法。我所说的方式是将您的主要代码包装在 try/except 块中,捕获 SystemExit
,然后在那里调用 os._exit
, 并且只在那里 !
这样你可以在代码的任何地方正常调用 sys.exit
,让它 "bubble-up" 到顶层,优雅地关闭所有文件和 运行 所有清理,然后最后调用 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!
如@MorganThrapp 所述,程序将在完成后自动干净地退出 运行。
不建议将 exit() 和 quit() 用于生产代码的原因是它会彻底终止您的程序。更好的做法是将代码放在 try-except 块 (https://wiki.python.org/moin/HandlingExceptions) 中。如果在 except 块中满足条件,程序将干净地结束,如果编程为,吐出引发的 exception/error 。这就是 "better" 方式。出于所有目的,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]
- 任何你想干净退出的地方,只需return退出你的主函数
这是我的代码:
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()
不推荐用于生产代码。
我的问题:是否有任何退出命令可以阻止您的代码继续运行而不显示任何消息或以 >>> 结尾,或者它只是关闭程序?
您不需要特定的命令。只要让你的程序走到尽头,它就会自行退出。如果你想过早地停止你的程序,你可以使用 sys.exit(0)
(确保你 import sys
)或 os._exit(0)
(import os
)来避免 all Python 关闭逻辑。
我也可以试试稍微安全一点的方法。我所说的方式是将您的主要代码包装在 try/except 块中,捕获 SystemExit
,然后在那里调用 os._exit
, 并且只在那里 !
这样你可以在代码的任何地方正常调用 sys.exit
,让它 "bubble-up" 到顶层,优雅地关闭所有文件和 运行 所有清理,然后最后调用 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!
如@MorganThrapp 所述,程序将在完成后自动干净地退出 运行。
不建议将 exit() 和 quit() 用于生产代码的原因是它会彻底终止您的程序。更好的做法是将代码放在 try-except 块 (https://wiki.python.org/moin/HandlingExceptions) 中。如果在 except 块中满足条件,程序将干净地结束,如果编程为,吐出引发的 exception/error 。这就是 "better" 方式。出于所有目的,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]
- 任何你想干净退出的地方,只需return退出你的主函数