You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何使用纯Python代码终止进程?替代killall与subprocess方案

Pure Python Way to Terminate a Process (No shell=True Needed)

Great question! Ditching shell=True is a smart call—it cuts down on security risks (like shell injection vulnerabilities) and makes your code work smoothly across different operating systems. Let’s walk through the best approaches to terminate the "Expert PDF" process using pure Python.

psutil is a robust third-party library that abstracts process management for Windows, macOS, and Linux. It’s the cleanest, most reliable way to handle this without shell commands.

Step 1: Install psutil

First, grab the library if you haven’t already:

pip install psutil

Step 2: Pure Python Code to Terminate the Process

Here’s a reusable function that safely locates and stops the target process:

import psutil

def terminate_process(process_name):
    # Loop through all running processes
    for proc in psutil.process_iter(['name']):
        try:
            # Match the process name (adjust for your OS: e.g., "ExpertPDF.exe" for Windows)
            if proc.info['name'] == process_name:
                # Gracefully ask the process to exit (use proc.kill() for forced termination)
                proc.terminate()
                # Optional: Wait up to 5 seconds for the process to shut down
                proc.wait(timeout=5)
                print(f"Successfully terminated process: {process_name}")
        except (psutil.NoSuchProcess, psutil.AccessDenied, psutil.ZombieProcess):
            # Handle edge cases: process already exited, no permissions, or zombie process
            pass

# Call the function with your target process name
terminate_process("Expert PDF")

Key Notes:

  • Process Name Accuracy: On Windows, process names usually end with .exe (e.g., ExpertPDF.exe), while macOS/Linux use the full app name like Expert PDF. Verify the exact name with tools like Activity Monitor (macOS) or Task Manager (Windows).
  • Graceful vs Forced Termination: proc.terminate() sends a polite exit signal (SIGTERM on Unix, WM_CLOSE on Windows). If the process refuses to exit, use proc.kill() to force it shut down (SIGKILL on Unix, TerminateProcess on Windows).

Alternative: Standard Library Only (Unix-Like Systems)

If you can’t use third-party libraries, you can rely on Python’s built-in os and subprocess modules (note: this only works on macOS/Linux):

import os
import signal
import subprocess

def terminate_process_unix(process_name):
    # Use pgrep to find PIDs without shell=True (pass arguments as a list)
    result = subprocess.run(
        ['pgrep', '-f', process_name],
        capture_output=True,
        text=True,
        check=False
    )
    
    if result.returncode == 0:
        pids = result.stdout.strip().split('\n')
        for pid in pids:
            try:
                # Send SIGTERM to the process
                os.kill(int(pid), signal.SIGTERM)
                print(f"Terminated process PID: {pid} ({process_name})")
            except OSError as e:
                print(f"Failed to terminate PID {pid}: {str(e)}")

terminate_process_unix("Expert PDF")

This method depends on pgrep, which is standard on most Unix-like systems but isn’t available on Windows. For Windows, you’d have to parse output from tasklist—a much more clunky approach, which is why psutil is the better cross-platform pick.


内容的提问来源于stack exchange,提问作者Wizard

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.29 08:20:03