Get Process By Name in Python

June 15, 2022 Python Multiprocessing

You can get a process by name by searching through all active child processes for a process with a given name.

In this tutorial you will discover how to get a process by name in Python.

Let's get started.

Need To Get a Process By Name

A process is a running instance of a computer program.

Every Python program is executed in a Process, which is a new instance of the Python interpreter. This process has the name MainProcess and has one thread used to execute the program instructions called the MainThread. Both processes and threads are created and managed by the underlying operating system.

Sometimes we may need to create new child processes in our program in order to execute code concurrently.

Python provides the ability to create and manage new processes via the multiprocessing.Process class.

You can learn more about multiprocessing in the tutorial:

In multiprocessing, we may need to get a process by name.

This may be for many reasons, such as:

How can we get a process by name?

How to Get a Process By Name

The Python standard library does not provide a mechanism to search through processes by name.

Instead, we can develop this functionality ourselves.

In this section we will explore how we might search for a process by its name.

Process Names

Python processes have names.

They are accessible via the name attribute on the multiprocessing.Process class instance for the process.

For example:

...
# get the process name
name = process.name

Process names are not unique.

The default names assigned to processes attempt to be unique, e.g. Process-1, Process-2, and so on. The name of processes can be changed at any time by the process itself or another process.

You can learn more about process names in the tutorial:

As such, we cannot rely on the name of a process being unique generally.

Nevertheless, within our application, we may assign distinct and meaningful names to processes. These names could then be used uniquely.

List Processes

In order to get a process by name, we need to be able to get a list of all processes, then search through them.

Within Python, we cannot get a list of all processes directly.

Instead, we can get a list of all active child processes for the current parent process.

This is available via the multiprocessing.active_children() function.

For example:

...
# get all child processes
processes = multiprocessing.active_children()

Search For Process

Once we have a list of active processes, we can search for a process with a given name.

This can be achieved by iterating through the list of processes and checking the name of each against a provided name.

For example:

...
# find a process with the name
for process in processes:
    # check for match
    if process.name == name:
        # ...

Once found, we can perform some action, such as:

Now that we know how to search for a process by its name, let's look at some worked examples.

Get a Child Process By Name

We can explore how to get a process instance by name.

In this example we will start a suite of child processes that will all block for a while. The parent process will then search for a process by its name and report all of its details.

First, we can develop the function used to search for a process by name.

The function takes the name of the process name to search for.

# return a child process with a given name or none
def get_process_by_name(name):
	# ...

First, we can get a list of all active child processes for the current parent process.

...
# get all child processes
processes = active_children()

Next, we can iterate the list of active children and check if the name of the process matches the provided name. If so, we can return the process instance.

...
# return the process with the name
for process in processes:
    # check for match
    if process.name == name:
        return process

Otherwise, we will return the value None, to indicate that no process with the name was found.

...
# no match
return None

Tying this together, the complete get_process_by_name() function is listed below.

# return a child process with a given name or none
def get_process_by_name(name):
    # get all child processes
    processes = active_children()
    # return the process with the name
    for process in processes:
        # check for match
        if process.name == name:
            return process
    # no match
    return None

Next, we can define a function to execute by each child process.

This function will just block for a few seconds, to give the children something to do.

The task() function below implements this.

# function executed in a child process
def task():
    # block for a while
    sleep(3)

Next, in the main process, we can configure a suite of processes to execute our task() function.

This can be achieved using a list comprehension.

...
# configure child processes
children = [Process(target=task) for _ in range(10)]

We can then start each child process. The main process can then block for a second to give the child processes a chance to start up.

...
# start child processes
for child in children:
    child.start()
# wait a moment
sleep(1)

We can then get a child process by name.

In this case, we will get the first child process, assigned the default name 'Process-1'. The result is then reported directly.

...
# get the child by name
child = get_process_by_name('Process-1')
print(f'Found: {child}')

Tying this together, the complete example is listed below.

# SuperFastPython.com
# example of getting a child process by name
from time import sleep
from multiprocessing import active_children
from multiprocessing import Process

# return a child process with a given name or none
def get_process_by_name(name):
    # get all child processes
    processes = active_children()
    # return the process with the name
    for process in processes:
        # check for match
        if process.name == name:
            return process
    # no match
    return None

# function executed in a child process
def task():
    # block for a while
    sleep(3)

# protect the entry point
if __name__ == '__main__':
    # configure child processes
    children = [Process(target=task) for _ in range(10)]
    # start child processes
    for child in children:
        child.start()
    # wait a moment
    sleep(1)
    # get the child by name
    child = get_process_by_name('Process-1')
    print(f'Found: {child}')

Running the example first configures and starts ten child processes.

Each child process runs, and blocks for a few seconds.

The main process blocks for a second, allowing the child processes to start.

The main process then gets a single process by name, and reports the result..

In this case, we can see that the process was located by name and its status is reported.

Note, the specific details of your process will differ each time the code is run.

Found: <Process name='Process-1' pid=26484 parent=26482 started>

Next, let's look at getting the process pid by name.

Get Child Process PID By Name

Each process has a unique process identifier or pid.

The pid is assigned by the underlying operating system, which also manages the life-cycle of the process.

You can learn more about process pids in the tutorial:

We can explore how to get a pid for a process by the process name.

In this example, we can update the example provided in the previous section to return the pid for the process, once it is located by name.

Firstly, we can change the name of the function to something more appropriate, such as get_process_pid_by_name().

# return a child process pid with a given name or none
def get_process_pid_by_name(name):
	# ...

Within this function, once the process is located by name, we can return the pid for the process.

The process pid can be accessed via the "pid" attribute of the process instance, for example:

...
# check for match
if process.name == name:
    return process.pid

Tying this together, the complete get_process_pid_by_name() function with these changes is listed below.

# return a child process pid with a given name or none
def get_process_pid_by_name(name):
    # get all child processes
    processes = active_children()
    # return the process with the name
    for process in processes:
        # check for match
        if process.name == name:
            return process.pid
    # no match
    return None

And that's it.

Tying this together, the complete example of getting a process pid by name is listed below.

# SuperFastPython.com
# example of getting a child process pid by name
from time import sleep
from multiprocessing import active_children
from multiprocessing import Process

# return a child process pid with a given name or none
def get_process_pid_by_name(name):
    # get all child processes
    processes = active_children()
    # return the process with the name
    for process in processes:
        # check for match
        if process.name == name:
            return process.pid
    # no match
    return None

# function executed in a child process
def task():
    # block for a while
    sleep(3)

# protect the entry point
if __name__ == '__main__':
    # configure child processes
    children = [Process(target=task) for _ in range(10)]
    # start child processes
    for child in children:
        child.start()
    # wait a moment
    sleep(1)
    # get the child process pid by name
    pid = get_process_pid_by_name('Process-1')
    print(f'Found: {pid}')

Running the example first configures and starts ten child processes.

Each child process runs, and blocks for a few seconds.

The main process blocks for a second, allowing the child processes to start.

The main process then gets the pid of the process with the given name, and reports the result.

Note, the process pid result will differ each time the code is run.

Found: 26501

Next, let's look at killing a process by name.

Kill Child Process By Name

We can explore killing a process by its name.

In this example, we can update the previous example to kill the process once found, then return the success or failure of the request, e.g. whether the process was found by name and killed or not.

We can kill a process by sending it a SIGKILL signal. This can be achieved by calling the kill() function on the multiprocessing.Process instance.

You can learn more about killing processes in the tutorial:

We can update the previous example to kill the process once found and return True, otherwise return False if the process with a given name could not be located.

First, we can give the function a more appropriate name, such as kill_child_process_by_name().

# returns true if the child process was located and kill, false otherwise
def kill_child_process_by_name(name):
	# ...

Next, we can call the kill() function on the process instance once found by name, then return True.

...
# check for match
if process.name == name:
    # kill the child process
    process.kill()
    return True

If the process was not found by name, we can return False.

...
# no match
return False

Tying this together, the complete kill_child_process_by_name() function with these changes is listed below.

# returns true if the child process was located and kill, false otherwise
def kill_child_process_by_name(name):
    # get all child processes
    processes = active_children()
    # locate child process with give name
    for process in processes:
        # check for match
        if process.name == name:
            # kill the child process
            process.kill()
            return True
    # no match
    return False

And that's it.

The complete example is listed below.

# SuperFastPython.com
# example of killing a child process by name
from time import sleep
from multiprocessing import active_children
from multiprocessing import Process

# returns true if the child process was located and kill, false otherwise
def kill_child_process_by_name(name):
    # get all child processes
    processes = active_children()
    # locate child process with give name
    for process in processes:
        # check for match
        if process.name == name:
            # kill the child process
            process.kill()
            return True
    # no match
    return False

# function executed in a child process
def task():
    # block for a while
    sleep(3)

# protect the entry point
if __name__ == '__main__':
    # configure child processes
    children = [Process(target=task) for _ in range(10)]
    # start child processes
    for child in children:
        child.start()
    # wait a moment
    sleep(1)
    # kill the child process by name
    outcome = kill_child_process_by_name('Process-1')
    print(f'Killed: {outcome}')

Running the example first configures and starts ten child processes.

Each child process runs, and blocks for a few seconds.

The main process blocks for a second, allowing the child processes to start.

The main process then requests that a process with the name 'Process-1' is located and killed.

The process is killed and the success of the request is reported.

Killed: True

Takeaways

You now know how to get a process by name in Python.