Multilingual content from IBKR

Close Navigation
Learn more about IBKR accounts
How to Stop Long-running Code in Python

How to Stop Long-running Code in Python

Posted December 13, 2021 at 11:25 am
Andrew Treadway

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 Campus that is provided by third-parties does NOT constitute a recommendation that you should contract for the services of that third party. Third-party participants who contribute to IBKR Campus 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 its permission. The views expressed in this material are solely those of the author and/or and Interactive Brokers 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 buy or sell any security. It should not be construed as research or investment advice or a recommendation to buy, sell or hold any security or commodity. 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.

IBKR Campus Newsletters

This website uses cookies to collect usage information in order to offer a better browsing experience. By browsing this site or by clicking on the "ACCEPT COOKIES" button you accept our Cookie Policy.