如何在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.
psutil Library (Recommended) 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-daemonbut you search forfud), replace the==withinin the condition. - Run the script with
sudoif the "fud" process is running as root—since you usedsudo topto see it, it might require elevated privileges to read its info.
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}'")
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 fudto confirm the exact process name—sometimes it might be something likefud.binorfud-serviceinstead of justfud. - 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

