[PYTHON] Control scripts with exceptions

#!/usr/bin/env python
# -*- coding: utf-8 -*-

import time


class StopWatching(Exception):
    pass


class RepeatWatching(Exception):
    pass


class ContinueWatching(Exception):
    time.sleep(5)


class Something():
    def __init__(self):
        print('start')
    def something(self):
        is_continue = False
        while True:
            try:
                if is_continue:
                    raise KeyboardInterrupt
                time.sleep(5)
            except KeyboardInterrupt:
                try:
                    self.option_controller()
                except StopWatching:
                    break
                except RepeatWatching:
                    print('repeat!')
                    is_continue = False
                except ContinueWatching:
                    print('to be continued...')
                    is_continue = True

    def option_controller(self):
        cmd = input('\n S: stop\n R: repeat\n C: continue\nOption: ')

        def stop_watching():
            raise StopWatching

        def repeat_watching():
            raise RepeatWatching

        def continue_watching():
            raise ContinueWatching()
        option = {'s': stop_watching,
                  'r': repeat_watching,
                  'c': continue_watching
                  }
        try:
            if cmd is None or cmd not in option:
                cmd = 'c'
            option[cmd.lower()]()
        except (StopWatching, RepeatWatching, ContinueWatching) as e:
            raise e


if __name__ == '__main__':
    s = Something()
    s.something()

Recommended Posts

Control scripts with exceptions
Control error wording with nginx
Control multiple robots with jupyter-lab
[Raspberry Pi] Stepping motor control with Raspberry Pi
Servo motor control with Raspberry Pi
Run scripts with Django's admin command
Try frequency control simulation with Python
Observe TCP congestion control with ns-3
[Tkinter] Control threads with Event object
Inverted pendulum with model predictive control
[systemd] Nvidia GPU fan control with rc.local
Make PLEN Control Server compatible with ViVi PLEN2
Infrared remote control reception with Intel Edison
[ev3dev × Python] SSH Control (remote control with keyboard)
Create a devilish picture with Blender scripts