How to stop long-running code in Python


python stopit package

Ever had long-running code that you don’t know when it’s going to finish running? If you have, then Python’s stopit library is for you. In a previous post, we talked about how to create a progress bar to monitor Python code. This post will show you how to automatically stop long-running code with the stopit package.

Getting started with stopit

To get started with stopit, you can install it via pip:


pip install stopit

In our first example, we’ll use a context manager to stop the code we want to execute after a timeout limit is reached.


import stopit

with stopit.ThreadingTimeout(5) as context_manager:
    
    # sample code we want to run...
    for i in range(10**8):
        i = i * 2
    
# Did code finish running in under 5 seconds?
if context_manager.state == context_manager.EXECUTED:
    print("COMPLETE...")

# Did code timeout?
elif context_manager.state == context_manager.TIMED_OUT:
    print("DID NOT FINISH...")

The result of running the above code will print out “DID NOT FINISH…”. Above, we just need to specify the number of seconds we want the timeout limit to be – in this case, 5. Inside of the with statement, we specify the code we want to run with the timeout limit. For your use case, you’ll just need to change the code within the with statement to whatever code you want to run.

Using a stopit decorator

Another way of using stopit to end code execution is with the timeoutable decorator. If you’re not familiar with decorators, check out this blog post.

Using the timeoutable decorator is handy when you’re calling a function and want to stop its execution once a certain amount of time has been reached. The only piece of code you need to add is the decorator at the top of whatever function you want, like below.


from stopit import threading_timeoutable as timeoutable

@timeoutable()
def count():

    for i in range(10**8):
        i = i * 2
    
    return i

Next, when you call the above function, you just need to add a parameter specifying the number of seconds you want to use for the timeout limit. If the timeout limit is reached, None is returned.

python stopit timeoutable decorator

If your function has parameters, you just need to add those in the function call along with the timeout parameter:


@timeoutable()
def count(upper):

    for i in range(upper):
        i = i * 2
    
    return i

result = count(timeout = 5, upper = 10**8)
print(result)

Lastly, it can be useful to know where in the function code the execution stops. There’s not an inherent way of getting that with stopit, but depending on what code you’re running it may be possible to find out. For example, in our function above, we can use the tqdm package to track the iterations in the for loop. To learn more about tqdm, check out this post.


from tqdm import tqdm

@timeoutable()
def count(upper):

    for i in tqdm(range(upper)):
        i = i * 2
    
    return i

As you can see in the snapshot below, tqdm prints out a progress bar keeping tracking of the number of iterations in the for loop. Once the time limit is reached (5 seconds in this case), we can tell that we timed out after 18,464,324 iterations.

python stopit tqdm

Conclusion

That’s it for now! You can check out the documentation for stopit by clicking here. If you want to learn more about Python, check out 365 Data Science by clicking here!