pyxx.dev.InterruptibleLoop

class pyxx.dev.InterruptibleLoop(throw_exception: bool = False)

Bases: object

Context manager to create an interruptible loop

This context manager allows users to interrupt and terminate a loop early by pressing Ctrl+c. This can be useful to stop a long process early while monitoring results (such as stopping training of a machine learning model). When interrupted, the context manager will change its interrupted attribute to True. Additionally, if the throw_exception option is enabled, an InterruptedError will be raised (which can be caught and handled as desired).

Examples

Basic usage:

>>> with pyxx.dev.InterruptibleLoop() as loop:
...     for i in range(1000):
...         # Do something
...
...         if loop.interrupted:
...             print('Loop was interrupted')
...             break

Example of using the throw_exception option:

>>> try:
...     with pyxx.dev.InterruptibleLoop(throw_exception=True) as loop:
...         for i in range(1000):
...             pass  # Do something
...
... except InterruptedError:
...     print('Loop was interrupted')
...
... else:
...     print('Loop was NOT interrupted')
Loop was NOT interrupted

Attributes

interrupted

Whether the loop has been interrupted

Methods

__init__([throw_exception])

__init__(throw_exception: bool = False) None
property interrupted: bool

Whether the loop has been interrupted