簡體   English   中英

還有其他方法可以在不使用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 ),這可以避免所有 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. 將所有代碼包裝在一個函數中,該函數通常稱為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. 任何您想干凈退出的地方,只需退出主函數即可

如@MorganThrapp所述,該程序完成運行后將自動干凈退出。

不建議在生產代碼中使用exit()和quit()的原因是,因為它會直接終止程序。 更好的做法是將代碼放在try-except塊中( https://wiki.python.org/moin/HandlingExceptions )。 如果在except塊中滿足該條件,則程序將干凈地結束,並且,如果進行了編程,則將拋出異常/錯誤。 那是“更好”的方式。 出於所有目的,quit()應該可以正常工作。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM