Stop/Kill a process from the command line after a certain amount of time Python

Are you looking to Stop/Kill a process from the Command line after a certain amount of time in Python? In this post, I will tell you how you can do that easily in Python.

If you are having any process or function that is running in a loop and you have no idea how to stop it after a certain period of time then you can use the below solution to quickly fix it.

Quick Fix to Stop/Kill a process from the Command line after a certain amount of Time

For the simplest approach, a timeout from the collection of GNU Coreutils (which is most likely already installed by default on most Linux systems) could be used:

timeout 20 ./sopare.py -l

Using the above code will kill or stop the process from being executed after 20 seconds. Additional options can be found in the user’s manual for this tool (man timeout). On non-GNU systems, if GNU Coreutils are installed at all, this program may be installed as gtimeout if GNU Coreutils are not installed.

Alternate Solution to Stop/Kill a Process from Command Line

You can follow the below alternate approach to stop or kill the process from the command line in Python.

./sopare.py -l &
sleep 20
kill "$!"

In the above code, you are specifying the python script that needs to be executed only for 20 seconds and then the kill command will stop the process completely.

Stop/kill a process from the command line after a certain amount of time Python

The process ID of the most recently initiated background process, in this case, your Python script, will be represented by the symbol $!.

If you are using the wait time in your python code to run different processes or code lines while the other process is waiting to get completed. Then you can use the below code to execute other code lines when you are using the wait time to complete.

./sopare.py -l & pid=$!
# whatever code here, as long as it doesn't change the pid variable
kill "$pid"

In the above code, PID is the process ID (You can find running Process IDs on Linux) that you want to kill and you can write your code in between the two lines shown above.

Then please follow us on FacebookTwitter and Subscribe to our Newsletter to join a great community of developers around the world. Let us know the questions and answer you want to cover in this blog.

Further Read:

  1. Trapping Rain Water Problem Python JAVA C++ Solution

Leave a Comment