onetop21 / interrupt_handler

Management interrupt on python app.

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

Interrupt Handler

Interrupt Handling Util for Python.

Installation

$ pip install InterruptHandler

How to Use

from interrupt_handler import InterruptHandler

# Break by Keyboard Interrupt (Default)
with InterruptHandler() as h:
  ...
  
# Break by checking interrupted flag.
with InterruptHandler(lambda: True) as h:
  if h.interrupted:
    break
  ...
  
 
# Propagate signal to parent.
with InterruptHandler():
  with InterruptHandler(propagate=True):
    ...

Callback customize

return False

Escape 'with statement' forcley.

return True

Switch 'interrupted flag'.

def callback():
  print('Interrupted by User.')
  return False
  
with InterruptHandler(callback) as h:
  ...

Example

import time
from interrupt_handler import InterruptHandler, default_callback

if __name__ == '__main__':
    import time
    main_loop = True
    sub_loop = True
    with InterruptHandler(default_callback('Locked', True)) as h1:
        while not h1.interrupted:
            print(f'MainLoop {time.time()}, {h1}, {h1.interrupted}')
            with InterruptHandler(default_callback('Message2')) as h2:
                while sub_loop:
                    print(f'SubLoop {time.time()}')
                    time.sleep(1)
            sub_loop = False
            time.sleep(1)
    main_loop = False

About

Management interrupt on python app.

License:MIT License


Languages

Language:Python 100.0%