殺死一個 Python 程序

Aditya Raj 2024年2月15日
  1. 使用鍵盤快捷鍵終止 Python 程序
  2. 使用程序名稱和 kill 命令殺死 Python 程序
  3. 使用程序名稱和 killall 命令終止 Python 程序
  4. 使用程序名稱和 pkill 命令終止 Python 程序
  5. まとめ
殺死一個 Python 程序

在使用 Python 程式設計時,有時我們的程式會陷入無限迴圈。在這種情況下,我們需要手動終止程式。

本文將討論殺死 Python 程序的不同方法。

使用鍵盤快捷鍵終止 Python 程序

殺死 Python 程序的最簡單方法是使用鍵盤快捷鍵 CTRL+C

每當 Python 程式執行到無限迴圈時,你可以在 IDE 或執行程式的終端中按 CTRL+C。按鍵後,Python 程序將立即終止。

有時,如果 Python 程式正忙於執行系統呼叫,你無法正常終止它。在這種情況下,我們必須從命令列手動終止 Python 程序。

使用命令列語句,我們需要向程式傳送一個 SIGTERM 訊號以終止。讓我們討論使用命令列終止 Python 程序的不同方法。

使用程序名稱和 kill 命令殺死 Python 程序

我們將按照這些步驟在 Linux 中使用 kill 命令殺死 Python 程序。首先,我們將使用 ps 命令和 grep 命令列出所有正在執行的 Python 程序,如下所示。

殺死 Python 程序

在這裡,ps 命令首先列出所有正在執行的程序。grep 命令過濾名稱中包含 Python 的所有程序,然後將輸出顯示給使用者。

你可以看到輸出中的第二項是一個數字。這個數字是 Python 程式的程序 ID。

使用以下語法,我們可以使用 process_idkill 命令來殺死 Python 程序。

kill process_id

這裡,process_id 是我們要終止的程式的程序 ID。你可以使用 kill 語句和程式的程序 ID 終止所有 Python 程序。

例如,我們可以使用以下命令殺死上圖中的第三個 Python 程序:

kill 9146

使用程序名稱和 killall 命令終止 Python 程序

我們可以使用 killall 命令同時殺死所有 Python 程序,而不是使用 kill 語句手動終止 Python 程序。

killall 命令將程序的名稱作為輸入。執行後,它會殺死所有具有給定名稱的程序。

你可以使用 killall 命令殺死所有 Python 程序,如下所示。

killall python

使用程序名稱和 pkill 命令終止 Python 程序

除了 killall 命令,我們可以使用 pkill 命令殺死 Python 程序。pkill 命令將程序的名稱作為輸入引數。

執行後,它將 SIGTERM 訊號傳送到輸入中給定名稱的所有程序。結果,具有給定名稱的所有程序都將終止。

使用以下語句,你可以將名稱 python 傳遞給 pkill 命令以終止 Python 程序。

pkill python

まとめ

在本文中,我們討論了殺死 Python 程序的不同方法。要殺死特定的 Python 程式,你可以將 psgrep 命令與 kill 命令一起使用。

要一次殺死所有 Python 程序,可以使用 killall 命令或 pkill 命令。

作者: Aditya Raj
Aditya Raj avatar Aditya Raj avatar

Aditya Raj is a highly skilled technical professional with a background in IT and business, holding an Integrated B.Tech (IT) and MBA (IT) from the Indian Institute of Information Technology Allahabad. With a solid foundation in data analytics, programming languages (C, Java, Python), and software environments, Aditya has excelled in various roles. He has significant experience as a Technical Content Writer for Python on multiple platforms and has interned in data analytics at Apollo Clinics. His projects demonstrate a keen interest in cutting-edge technology and problem-solving, showcasing his proficiency in areas like data mining and software development. Aditya's achievements include securing a top position in a project demonstration competition and gaining certifications in Python, SQL, and digital marketing fundamentals.

GitHub

相關文章 - Python Process