LoginSignup
1

More than 5 years have passed since last update.

例外をつかってスクリプトをコントロールする

Posted at
#!/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()

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1