pyxx.dev.InterruptibleLoop¶
- class pyxx.dev.InterruptibleLoop(throw_exception: bool = False)¶
Bases:
objectContext 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 itsinterruptedattribute toTrue. Additionally, if thethrow_exceptionoption is enabled, anInterruptedErrorwill 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_exceptionoption:>>> 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
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