如何在 Python 中終止 Windows 上正在執行的程序?
在深入研究 Windows 作業系統上的 Python 開發領域時,無疑會出現需要終止正在執行的程序的情況。此類終止背後的動機可能涵蓋各種場景,包括無響應、過度佔用資源或僅僅需要停止指令碼執行。在這篇綜合文章中,我們將探討使用 Python 在 Windows 上終止正在執行的程序的各種方法。透過利用“os”模組、“psutil”庫和`subprocess`模組,我們將為自身配備一套多功能工具包來處理此項重要任務。
方法 1:使用多功能的“os”模組
`os` 模組是 Python 與作業系統互動的基石,擁有豐富的功能庫。其中,`system()` 函式提供了一個執行作業系統命令的途徑。值得注意的是,Windows 利用 `taskkill` 命令來終止活動程序。
示例:利用“os”模組
在接下來的示例中,我們將使用 `os` 模組來終止著名的記事本應用程式
import os
# The process name to be brought to an abrupt halt
process_name = "notepad.exe"
# Employing the taskkill command to terminate the process
result = os.system(f"taskkill /f /im {process_name}")
if result == 0:
print(f"Instance deletion successful: {process_name}")
else:
print("Error occurred while deleting the instance.")
輸出
Deleting instance \DESKTOP-LI99O93\ROOT\CIMV2:Win32_Process.Handle="1234" Instance deletion successful.
此說明性程式碼片段使用 `taskkill` 命令以及`/f`(強制)和`/im`(影像名稱)標誌來強制終止由指定影像名稱標識的程序。
方法 2:利用強大的“psutil”庫
`psutil` 庫提供了一個強大的跨平臺工具集,用於訪問系統資訊和操作正在執行的程序。在深入利用 `psutil` 之前,我們必須首先確保它的存在,方法是執行以下安裝命令
pip install psutil
成功安裝後,我們可以利用 `psutil` 的功能來終止活動程序。
示例:利用“psutil”庫
在接下來的示例中,我們將使用 `psutil` 庫來終止著名的記事本應用程式
import psutil
# The process name to be terminated
process_name = "notepad.exe"
# Iterating through all running processes
for proc in psutil.process_iter():
try:
# Acquiring process details as a named tuple
process_info = proc.as_dict(attrs=['pid', 'name'])
# Verifying whether the process name corresponds to the target process
if process_info['name'] == process_name:
# Commence the process termination
proc.terminate()
print(f"Instance deletion successful: {process_info}")
except (psutil.NoSuchProcess, psutil.AccessDenied, psutil.ZombieProcess):
# Prudently handling potential exceptions arising during process information retrieval
pass
輸出
Deleting instance \DESKTOP-LI99O93\ROOT\CIMV2:Win32_Process.Handle="5678" Instance deletion successful.
此示例片段闡明瞭我們的方法:我們使用 `psutil.process_iter()` 迭代所有正在執行的程序。透過利用 `as_dict()` 方法,我們以命名元組的形式獲取程序資訊。如果程序名稱與目標程序一致,我們將立即透過 `terminate()` 方法終止它。
方法 3:釋放“subprocess”模組的力量
Python 的“subprocess”模組使我們能夠生成新程序,與它們的輸入/輸出/錯誤管道建立連線,並檢索它們的返回程式碼。我們可以利用此模組執行 `taskkill` 命令並有效地終止正在執行的程序。
示例:利用“subprocess”模組
在本例中,我們將演示使用強大的“subprocess”模組終止記事本應用程式
import subprocess
# The process name to be terminated
process_name = "notepad.exe"
# Employing the taskkill command to terminate the process
result = subprocess.run(f"taskkill /f /im {process_name}", shell=True)
if result.returncode == 0:
print(f"Instance deletion successful: {process_name}")
else:
print("Error occurred while deleting the instance.")
輸出
Deleting instance \DESKTOP-LI99O93\ROOT\CIMV2:Win32_Process.Handle="9012" Instance deletion successful.
在此示例中,我們依靠 `subprocess.run()` 函式來執行帶有`/f` 和`/im` 標誌的 `taskkill` 命令。 `shell=True` 引數在 Windows 命令 shell 中執行命令時變得不可或缺。
結論
在整個深入探討中,我們闡明瞭三種不同的方法來使用 Python 終止 Windows 上正在執行的程序。透過使用 `os` 模組,我們能夠執行作業系統命令。 `psutil` 庫成為一個強大的工具,為我們提供了一個全面的、跨平臺的解決方案,用於系統資訊檢索和程序操作。此外,“subprocess”模組開啟了新的維度,使我們能夠輕鬆地生成程序和執行命令。
每種方法都有其自身的優點,適合特定的專案需求。在進行程序終止工作時,務必謹慎行事,並瞭解其中可能存在的風險,例如資料丟失或系統不穩定。
資料結構
網路
關係資料庫管理系統
作業系統
Java
iOS
HTML
CSS
Android
Python
C 程式設計
C++
C#
MongoDB
MySQL
Javascript
PHP