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

如何在Python中根据进程名称获取进程ID(PID)

Got it, let's get your Python script working to find the PID for that "fud" process! I'll walk you through two reliable approaches, plus some troubleshooting tips since you can see the process running with sudo top but your script isn't picking it up.

This is the cleanest, cross-platform way to handle process queries in Python. It abstracts away all the messy system command parsing.

First, install it if you haven't already:

pip install psutil

Then use this script to find the PID(s) by process name:

import psutil

def find_pids_by_process_name(process_name):
    matching_pids = []
    # Iterate through all running processes
    for proc in psutil.process_iter(['name', 'pid']):
        try:
            # Exact match for the process name—adjust to `in` if you need partial matches
            if proc.info['name'] == process_name:
                matching_pids.append(proc.info['pid'])
        # Skip processes we can't access (common with system/root processes)
        except (psutil.NoSuchProcess, psutil.AccessDenied, psutil.ZombieProcess):
            continue
    return matching_pids

# Test it with your target process
target = "fud"
pids = find_pids_by_process_name(target)

if pids:
    print(f"Found PID(s) for '{target}': {', '.join(map(str, pids))}")
else:
    print(f"No running processes found with name '{target}'")

Quick Notes:

  • If you need to match partial process names (like if the full name is fud-daemon but you search for fud), replace the == with in in the condition.
  • Run the script with sudo if the "fud" process is running as root—since you used sudo top to see it, it might require elevated privileges to read its info.
2. Use subprocess with System Commands (No Third-Party Libraries)

If you can't install psutil, you can call Linux's native ps command directly and parse the output:

import subprocess
import re

def find_pids_by_process_name(process_name):
    pids = []
    try:
        # Get full process list with `ps aux`
        output = subprocess.check_output(['ps', 'aux'], text=True)
        # Regex to capture PID (second column) and match the exact process name at the end of the line
        regex_pattern = re.compile(r'\s+(\d+)\s+.+\s+' + re.escape(process_name) + r'$')
        
        for line in output.splitlines():
            match = regex_pattern.search(line)
            if match:
                pids.append(match.group(1))
    except subprocess.CalledProcessError:
        print("Error running process query")
    return pids

# Test the function
target = "fud"
pids = find_pids_by_process_name(target)

if pids:
    print(f"Found PID(s) for '{target}': {', '.join(pids)}")
else:
    print(f"No running processes found with name '{target}'")
Troubleshooting Tips

Since you can see the process in sudo top but your script isn't finding it, check these:

  • Permissions: Run your script with sudo (e.g., sudo python3 your_script.py). Root processes often restrict access to their info from non-root users.
  • Exact Process Name: Use ps aux | grep fud to confirm the exact process name—sometimes it might be something like fud.bin or fud-service instead of just fud.
  • Case Sensitivity: Linux process names are case-sensitive—make sure your script uses the exact capitalization of the process name you see in top.

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.20 07:13:13