stop code execution in python after certain time

How to Stop Python Code After Certain Amount of Time

Python allows you to build long running processes and functions. But sometimes you may want to stop code execution after certain amount of time. If you are building long running processes, it is advisable to add timeout-like mechanisms to ensure that they don’t run forever and consume unnecessary resources. In this article, we will learn how to stop python code after certain amount of time.


How to Stop Python Code After Certain Amount of Time

Here are the steps to setup a timeout for python function.


1. Import Required Libraries

First, we import required libraries like multiprocessing and time.

import multiprocessing
import time


2. Create Python Function

Next, we create a python function that takes a long time to complete.

def foo(n):
    for i in range(10000 * n):
        print i
        time.sleep(1)

The above functions basically prints 1 sequential number ( e.g 0, 1, 2, 3, … ) every 1 second, for 10000*n seconds, where n is user input. So it takes a lot of time to complete, as you can see.


3. Add Timeout Code

Next, we add the code to call function foo, and timeout after 10 seconds.

if __name__ == '__main__':
    # Start foo as a process
    p = multiprocessing.Process(target=foo, name="Foo", args=(10,))
    p.start()

    # Wait 10 seconds for foo
    time.sleep(10)

    # Terminate foo
    p.terminate()

    # Cleanup
    p.join()

In the above code, we start a process to run foo function, and pass an argument=10. So it will run for 100,000 seconds. p.start() function will start the process. time.sleep(10) will wait for foo function to run for 10 seconds. After the timeout period is over, p.terminate() function will terminate foo function. p.join() is used to continue execution of main thread.

Here is the complete code for your references

#!/usr/bin/env python 
#test.py

import multiprocessing
import time

def foo(n):
    for i in range(10000 * n):
        print i
        time.sleep(1)

if __name__ == '__main__':
    # Start foo as a process
    p = multiprocessing.Process(target=foo, name="Foo", args=(10,))
    p.start()

    # Wait 10 seconds for foo
    time.sleep(10)

    # Terminate foo
    p.terminate()

    # Cleanup
    p.join()

If you run the above script, it will run for 10 seconds and terminate after that.

There are also other ways to do the same thing. For example, you can also use signal module to implement a timeout for function call.

Also read:

How to Convert Bytes to String in Python
How to Store Output of Cut Command in Shell Variable
How to Use Shell Variables in Awk Script
How to Setup SSH Keys in Linux
How to Create Nested Directory in Python

Leave a Reply

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