How to Stop Long-running Code in Python



Blogger,, and Senior Data Scientist

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:
# 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
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.

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

def count(upper):
    for i in range(upper):
        i = i * 2
    return i
result = count(timeout = 5, upper = 10**8)

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 tqdmcheck out this post.

from tqdm import tqdm
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.


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!

Visit for additional insight on this topic:

Disclosure: Interactive Brokers

Information posted on IBKR Traders’ Insight that is provided by third-parties and not by Interactive Brokers does NOT constitute a recommendation by Interactive Brokers that you should contract for the services of that third party. Third-party participants who contribute to IBKR Traders’ Insight are independent of Interactive Brokers and Interactive Brokers does not make any representations or warranties concerning the services offered, their past or future performance, or the accuracy of the information provided by the third party. Past performance is no guarantee of future results.

This material is from and is being posted with permission from The views expressed in this material are solely those of the author and/or and IBKR is not endorsing or recommending any investment or trading discussed in the material. This material is not and should not be construed as an offer to sell or the solicitation of an offer to buy any security. To the extent that this material discusses general market activity, industry or sector trends or other broad based economic or political conditions, it should not be construed as research or investment advice. To the extent that it includes references to specific securities, commodities, currencies, or other instruments, those references do not constitute a recommendation to buy, sell or hold such security. This material does not and is not intended to take into account the particular financial conditions, investment objectives or requirements of individual customers. Before acting on this material, you should consider whether it is suitable for your particular circumstances and, as necessary, seek professional advice.

In accordance with EU regulation: The statements in this document shall not be considered as an objective or independent explanation of the matters. Please note that this document (a) has not been prepared in accordance with legal requirements designed to promote the independence of investment research, and (b) is not subject to any prohibition on dealing ahead of the dissemination or publication of investment research.

Any trading symbols displayed are for illustrative purposes only and are not intended to portray recommendations.