Last Updated on September 12, 2022
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:
- We don’t have the pid of the process.
- Report details of the process.
- Send a signal to the process, like SIGKILL to kill it.
How can we get a process by name?
Run loops using all CPUs, download your FREE book to learn how.
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:
1 2 3 |
... # 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:
1 2 3 |
... # 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:
1 2 3 4 5 6 |
... # 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:
- Return the process with the name.
- Retrieve details of the process, like the pid.
- Send a signal to the process.
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.
1 2 3 |
# 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.
1 2 3 |
... # 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.
1 2 3 4 5 6 |
... # 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.
1 2 3 |
... # no match return None |
Tying this together, the complete get_process_by_name() function is listed below.
1 2 3 4 5 6 7 8 9 10 11 |
# 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.
1 2 3 4 |
# 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.
1 2 3 |
... # 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.
1 2 3 4 5 6 |
... # 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.
1 2 3 4 |
... # 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.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 |
# 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.
1 |
Found: <Process name='Process-1' pid=26484 parent=26482 started> |
Next, let’s look at getting the process pid by name.
Free Python Multiprocessing Course
Download your FREE multiprocessing PDF cheat sheet and get BONUS access to my free 7-day crash course on the multiprocessing API.
Discover how to use the Python multiprocessing module including how to create and start child processes and how to use a mutex locks and semaphores.
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().
1 2 3 |
# 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:
1 2 3 4 |
... # 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.
1 2 3 4 5 6 7 8 9 10 11 |
# 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.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 |
# 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.
1 |
Found: 26501 |
Next, let’s look at killing a process by name.
Overwhelmed by the python concurrency APIs?
Find relief, download my FREE Python Concurrency Mind Maps
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().
1 2 3 |
# 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.
1 2 3 4 5 6 |
... # 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.
1 2 3 |
... # no match return False |
Tying this together, the complete kill_child_process_by_name() function with these changes is listed below.
1 2 3 4 5 6 7 8 9 10 11 12 13 |
# 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.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 |
# 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.
1 |
Killed: True |
Further Reading
This section provides additional resources that you may find helpful.
Python Multiprocessing Books
- Python Multiprocessing Jump-Start, Jason Brownlee (my book!)
- Multiprocessing API Interview Questions
- Multiprocessing API Cheat Sheet
I would also recommend specific chapters in the books:
- Effective Python, Brett Slatkin, 2019.
- See: Chapter 7: Concurrency and Parallelism
- High Performance Python, Ian Ozsvald and Micha Gorelick, 2020.
- See: Chapter 9: The multiprocessing Module
- Python in a Nutshell, Alex Martelli, et al., 2017.
- See: Chapter: 14: Threads and Processes
Guides
- Python Multiprocessing: The Complete Guide
- Python Multiprocessing Pool: The Complete Guide
- Python ProcessPoolExecutor: The Complete Guide
APIs
References
Takeaways
You now know how to get a process by name in Python.
Do you have any questions?
Ask your questions in the comments below and I will do my best to answer.
Photo by Emiliano Bar on Unsplash
Do you have any questions?