terminate python subprocess

How to Terminate Python Subprocess

Python allows you to run system commands using subprocesses. They allow you to spawn new processes, connect to their input/output/error and get their return codes. Subprocesses are very useful to run shell commands from Python. But sometimes you may need to terminate a running subprocess. In this article, we will learn how to terminate python subprocess.

For this purpose, we will create a process group that allows you to send signals to all processes in process group. To do this, we will attach a session id to the parent process of the shell process (subprocess). This will make it the leader of the group of processes. Thereafter, when you send a signal to the process group leader it will be sent to all processes in the group.


How to Terminate Python Subprocess

Here is a python command generally used to create subprocess.

p = subprocess.Popen(cmd, stdout=subprocess.PIPE, shell=True)

Instead of creating the subprocess using above command, we slightly modify to be it as following.

p = subprocess.Popen(cmd, stdout=subprocess.PIPE, shell=True, preexec_fn=os.setsid) 

In the above command, the os.setsid() is passed in the argument preexec_fn so it is run after the fork() but before exec() to run the shell.

Once you create subprocess with the above command, you can always refer to it using its id attribute as p.id and send a SIGTERM signal to it.

Here is the full code to terminate a subprocess created in python.

import os
import signal
import subprocess


pro = subprocess.Popen(cmd, stdout=subprocess.PIPE, 
                       shell=True, preexec_fn=os.setsid) 

os.killpg(os.getpgid(pro.pid), signal.SIGTERM)  

In the above command, we use killpg command to send the terminate signal to all the process groups.

In this article, we have learnt how to terminate python subprocess using process group. You can modify these commands as per your requirement.

Also read:

How to Convert Epub to PDF in Linux
How to Convert Docx to PDF in Linux
How to Remove Yum Repository in Linux
How to Remove Repository in Ubuntu
How to Deny Access to Users or Groups

Leave a Reply

Your email address will not be published. Required fields are marked *