杰瑞科技汇

Python如何获取进程名称?

Of course! In Python, getting the name of the current process is straightforward. The primary module you'll use is the built-in os module.

Python如何获取进程名称?-图1
(图片来源网络,侵删)

Here’s a complete guide, from the simplest case to more advanced scenarios.

The Simplest Case: os.getpid()

The most common task is to get the Process ID (PID), which is a unique number assigned by the operating system to every running process. You can use os.getpid() for this.

import os
# Get the Process ID (PID) of the current process
pid = os.getpid()
print(f"The current process ID is: {pid}")

Output:

The current process ID is: 12345  # The number will be different on your system

Getting the Process Name (Command)

Getting the actual "name" (e.g., python, my_script.py, /usr/bin/python3) is a bit more involved because it's not directly provided by Python's standard library. You need to inspect the command-line arguments of the process.

Python如何获取进程名称?-图2
(图片来源网络,侵删)

The most reliable way to do this is by reading the /proc filesystem on Linux and macOS. On Windows, you can use the psutil library for a cross-platform solution.

Method A: Reading /proc/self/comm (Linux/macOS)

The /proc filesystem provides a lot of information about running processes. The /proc/self/comm file contains the command name of the current process.

import os
try:
    # Read the command name from the /proc filesystem
    # This is the most direct way on Linux/macOS
    with open('/proc/self/comm', 'r') as f:
        process_name = f.read().strip()
    print(f"The process name (from /proc/self/comm) is: {process_name}")
except FileNotFoundError:
    # This block will run on Windows or systems without /proc
    print("The /proc filesystem is not available on this OS.")
    print("Consider using the psutil library for a cross-platform solution.")

Output:

The process name (from /proc/self/comm) is: python

Method B: The Cross-Platform Solution with psutil

The psutil (process and system utilities) library is the best choice for cross-platform process management. It's not built-in, so you need to install it first.

Installation:

pip install psutil

Usage: The psutil.Process class gives you access to a wealth of information about a process.

import psutil
import os
pid = os.getpid()
current_process = psutil.Process(pid)
# Get the name of the process executable
process_name = current_process.name()
# Get the full command line used to start the process
cmdline = current_process.cmdline()
print(f"Process ID: {pid}")
print(f"Process Name (executable): {process_name}")
print(f"Full Command Line: {cmdline}")

Example Output:

Process ID: 54321
Process Name (executable): python3
Full Command Line: ['/usr/bin/python3', '/path/to/your/script.py', '--arg1', 'value1']

Notice how cmdline gives you the full path to the script and any arguments, which is often more useful than just the executable name.


Practical Example: Logging Your Own Process Name

A common use case is to log the process ID and name, especially in applications that use multiprocessing or run as background services (daemons).

import os
import psutil
import logging
import time
def setup_logging():
    """Configures basic logging."""
    logging.basicConfig(
        level=logging.INFO,
        format='%(asctime)s - %(levelname)s - %(message)s'
    )
def get_process_info():
    """Gathers and returns information about the current process."""
    pid = os.getpid()
    process = psutil.Process(pid)
    # Get the full path to the script being run
    try:
        # cmdline[0] is the path to the script/interpreter
        script_name = process.cmdline()[0]
    except (IndexError, psutil.AccessDenied):
        script_name = "unknown"
    return {
        "pid": pid,
        "name": process.name(),
        "script": script_name
    }
if __name__ == "__main__":
    setup_logging()
    # Log initial process info
    info = get_process_info()
    logging.info(f"Application started. Process Info: {info}")
    # Simulate some work
    logging.info("Doing some work...")
    time.sleep(5)
    # Log again before exiting
    logging.info("Work finished. Shutting down.")

Example Log Output:

2025-10-27 10:30:00,123 - INFO - Application started. Process Info: {'pid': 9876, 'name': 'python3', 'script': '/path/to/your/script.py'}
2025-10-27 10:30:00,125 - INFO - Doing some work...
2025-10-27 10:30:05,126 - INFO - Work finished. Shutting down.

Summary: Which Method to Use?

Your Goal Recommended Method Why?
Get the unique Process ID (PID) os.getpid() It's built-in, fast, and universally available.
Get the executable name (python, node) psutil.Process(pid).name() Cross-platform, reliable, and easy to use. Requires pip install psutil.
Get the full command/script path psutil.Process(pid).cmdline() The most informative way to identify the specific script or application. Also cross-platform.
Quick & dirty on Linux/macOS only open('/proc/self/comm').read() No external dependencies, but not portable to Windows.
分享:
扫描分享到社交APP
上一篇
下一篇