HOWTO · Python

如何在 Python 中結束程式

在 Python 中,很多內建函式如 quit()、exit()、sys.exit()和 os.exit()都是用來結束 Python 程式的。

本頁內容

在 PHP 中,die() 命令可以終止正在執行的指令碼。同樣,Python 指令碼也可以通過使用不同的內建函式如 quit()、exit()、sys.exit() 和 os.exit() 來終止。Python 按照從上到下的順序執行指令,按照標準,執行程式碼中定義的迴圈;但是,當 Python 直譯器到達檔案 EOF 的末端時,無法讀取更多的指令,所以結束執行。

本文將介紹 Python 中結束程式的方法。

用 quit() 方法結束 Python 程式

使用內建函式終止 Python 指令碼的一個簡單而有效的方法是 quit() 方法,這個函式只能在 Python 直譯器中利用。當這個命令執行時,它會在作業系統中產生一個 SystemExit 異常。完整的示例程式碼如下。

for test in range(10):
    if test == 5:
        print(quit)
        quit()
        print(test)

輸出:

0
1
2
3
4
Use quit() or Ctrl-Z plus Return to exit

用 exit() 方法結束 Python 程式

它的功能與 quit() 方法相同,但你不需要為此匯入 Python 庫。完整的示例程式碼如下。

for test in range(10):
    if test == 5:
        print(exit)
        exit()
    print(test)

輸出:

0
1
2
3
4
Use exit() or Ctrl-Z plus Return to exit

用 sys.exit() 方法結束 Python 程式

這個方法比 quit() 和 exit() 方法更好。語法是:

sys.exit([arg])

語法中的 arg 是可選的。大多數情況下,它是一個整數值,但也可以傳遞字串值。零引數值被認為是成功終止的最佳情況。完整的示例程式碼如下。

import sys

weight = 70
if weight < 80:
    sys.exit("weight less than 80")
else:
    print("weight is not less than 80")

輸出:

SystemExit: weight less than 80

用 os.exit() 方法結束 Python 程式

這個方法用於終止像指令碼中的子程序一樣具有某種特殊狀態的程序。子程序可以使用 os.fork() 方法來建立。os.fork() 命令在 Linux 上可以有效地工作,但是,你必須使用 Windows 專用的 Cygwin。它的參考資料在這裡。

完整的示例程式碼如下。

import os

parent_id = os.fork()
if parent_id > 0:
    print("\nIn parent process")
    info = os.waitpid(parent_id, 0)
    if os.WIFEXITED(info[1]):
        code = os.WEXITSTATUS(info[1])
        print("Child's exit code:", code)
else:
    print("child process")
    print("Process ID:", os.getpid())
    print("Test Code")
    print("Child exiting..")
    os._exit(os.EX_OK)

os.wait() 方法將返回子程序 ID 及其終止狀態。我們將使用 os._exit() 方法獲得退出程式碼。

輸出:

AttributeError: module 'os' has no attribute 'fork'

まとめ

在上述所有方法中,sys.exit() 方法是首選。另一方面,os.exit() 命令應該用於特定情況和即時終止。