コード例 #1
0
ファイル: menu.py プロジェクト: evido3s/ntw-menu
 def show(self):
     from termenu import keyboard
     ansi.hide_cursor()
     if self.filter_text == None:
         self._print_menu()
     elif str(self.filter_text) == ('[]' or ''):
         self.filter_text = None
         self._print_menu()
     else:
         self._on_key('')
         self._print_menu()
     ansi.save_position()
     try:
         for key in keyboard.keyboard_listener(self._heartbeat):
             stop = self._on_key(key)
             if stop:
                 return self.get_result()
             self._goto_top()
             if str(self.filter_text) == ('[]' or ''):
                 self.filter_text = None
                 self._print_menu()
             else:
                 self._print_menu()
     finally:
         self._clear_menu()
         ansi.show_cursor()
コード例 #2
0
 def show(self):
     from termenu import keyboard
     self._print_menu()
     ansi.save_position()
     ansi.hide_cursor()
     try:
         for key in keyboard.keyboard_listener(self._heartbeat):
             stop = self._on_key(key)
             if stop:
                 return self.get_result()
             self._goto_top()
             self._print_menu()
     finally:
         self._clear_menu()
         ansi.show_cursor()
コード例 #3
0
 def show(self):
     from termenu import keyboard
     self._print_menu()
     ansi.save_position()
     ansi.hide_cursor()
     try:
         for key in keyboard.keyboard_listener(self._heartbeat):
             stop = self._on_key(key)
             if stop:
                 return self.get_result()
             self._goto_top()
             self._print_menu()
     finally:
         self._clear_menu()
         ansi.show_cursor()
コード例 #4
0
 def show(self):
     import keyboard
     ansi.hide_cursor()
     self._print_menu(rewind=False)
     try:
         for key in keyboard.keyboard_listener():
             if key == "enter":
                 self._clear_menu()
                 ansi.write(self.options[self.cursor])
                 return self.options[self.cursor]
             elif key == "esc":
                 self._clear_menu()
                 ansi.write("<esc>")
                 return None
             elif key == "left":
                 self.cursor = max(0, self.cursor - 1)
             elif key == "right":
                 self.cursor = min(len(self.options) - 1, self.cursor + 1)
             self._print_menu(rewind=True)
     finally:
         ansi.show_cursor()
         ansi.write("\n")
コード例 #5
0
 def show(self):
     from termenu import keyboard
     ansi.hide_cursor()
     self._print_menu(rewind=False)
     try:
         for key in keyboard.keyboard_listener():
             if key == "enter":
                 self._clear_menu()
                 ansi.write(self.options[self.cursor])
                 return self.options[self.cursor]
             elif key == "esc":
                 self._clear_menu()
                 ansi.write("<esc>")
                 return None
             elif key == "left":
                 self.cursor = max(0, self.cursor - 1)
             elif key == "right":
                 self.cursor = min(len(self.options) - 1, self.cursor + 1)
             self._print_menu(rewind=True)
     finally:
         ansi.show_cursor()
         ansi.write("\n")
コード例 #6
0
ファイル: sync.py プロジェクト: phistakis/easypy
def iter_wait(
        timeout, pred=None, sleep=0.5, message=None,
        progressbar=True, throw=True, allow_interruption=False, caption=None,
        log_interval=10 * MINUTE, log_level=logging.DEBUG):

    # Calling wait() with a predicate and no message is very not informative
    # (throw=False or message=False disables this behavior)
    if message is False:
        message = None
    elif throw and pred and not message:
        raise Exception(
            "Function iter_wait()'s parameter `message` is required if "
            "`pred` is passed",
        )

    if timeout is None:
        msg = "Waiting indefinitely%s"
    else:
        msg = "Waiting%%s up to %s" % time_duration(timeout)

    if message is None:
        if caption:
            message = "Waiting %s timed out after {duration:.1f} seconds" % (caption,)
        elif pred:
            message = "Waiting on predicate (%s) timed out after {duration:.1f} seconds" % (pred,)
        else:
            message = "Timed out after {duration:.1f} seconds"

    if pred:
        pred_decorator = kwargs_resilient(negligible=['is_final_attempt'])
        if hasattr(pred, "__iter__"):
            pred = make_multipred(map(pred_decorator, pred))
        else:
            pred = pred_decorator(pred)
        if not caption:
            caption = "on predicate (%s)" % pred
    else:
        pred = lambda **kwargs: False
        throw = False

    if caption:
        msg %= " %s" % (caption,)
    else:
        msg %= ""

    if isinstance(sleep, tuple):
        data = list(sleep)  # can't use nonlocal since this module is indirectly used in python2

        def sleep():
            cur, mx = data
            try:
                return cur
            finally:
                data[0] = min(mx, cur * 1.5)

    if not IS_A_TTY:
        # can't interrupt
        allow_interruption = False
        progressbar = False

    if progressbar and threading.current_thread() is not threading.main_thread():
        # prevent clutter
        progressbar = False

    if allow_interruption:
        msg += " (hit <ESC> to continue)"

    l_timer = Timer(expiration=timeout)
    log_timer = Timer(expiration=log_interval)

    with ExitStack() as stack:
        if progressbar:
            from .logging import PROGRESS_BAR
            pr = stack.enter_context(PROGRESS_BAR())
            pr.set_message(msg)

        while True:
            s_timer = Timer()
            expired = l_timer.expired
            last_exc = None
            try:
                ret = pred(is_final_attempt=bool(expired))
            except PredicateNotSatisfied as _exc:
                if getattr(_exc, "duration", 0):
                    # this exception was raised by a nested 'wait' call - don't swallow it!
                    raise
                if log_timer.expired:
                    log_timer.reset()
                    _logger.log(log_level, 'Still waiting after %r: %s', l_timer.elapsed, _exc.message)
                last_exc = _exc
                ret = None
            else:
                if ret not in (None, False):
                    yield ret
                    return
            if expired:
                duration = l_timer.stop()
                start_time = l_timer.start_time
                if throw:
                    if last_exc:
                        last_exc.add_params(duration=duration, start_time=start_time)
                        raise last_exc
                    if callable(message):
                        message = message()
                    raise TimeoutException(message, duration=duration, start_time=start_time)
                yield None
                return
            yield l_timer.remain
            sleep_for = sleep() if callable(sleep) else sleep
            if allow_interruption:
                from termenu.keyboard import keyboard_listener
                timer = Timer(expiration=sleep_for - s_timer.elapsed)
                for key in keyboard_listener(heartbeat=0.25):
                    if key == "esc":
                        yield None
                        return
                    if key == "enter":
                        break
                    if timer.expired:
                        break
            else:
                s_timeout = max(0, sleep_for - s_timer.elapsed)
                if l_timer.expiration:
                    s_timeout = min(l_timer.remain, s_timeout)
                time.sleep(s_timeout)
コード例 #7
0
def iter_wait(timeout, pred=None, sleep=0.5, message=None,
              progressbar=True, throw=True, allow_interruption=False, caption=None):

    if timeout is None:
        msg = "Waiting indefinitely%s"
    else:
        msg = "Waiting%%s up to %s" % time_duration(timeout)

    if message is None:
        if caption:
            message = "Waiting %s timed out after {duration:.1f} seconds" % (caption,)
        elif pred:
            message = "Waiting on predicate (%s) timed out after {duration:.1f} seconds" % (pred,)
        else:
            message = "Timed out after {duration:.1f} seconds"

    if pred:
        if hasattr(pred, "__iter__"):
            pred = make_multipred(pred)
        if not caption:
            caption = "on predicate (%s)" % pred
    else:
        pred = lambda: False
        throw = False

    if caption:
        msg %= " %s" % (caption,)
    else:
        msg %= ""

    if isinstance(sleep, tuple):
        data = list(sleep)  # can't use nonlocal since this module is indirectly used in python2

        def sleep():
            cur, mx = data
            try:
                return cur
            finally:
                data[0] = min(mx, cur*1.5)

    if not IS_A_TTY:
        # can't interrupt
        allow_interruption = False
        progressbar = False

    if progressbar and threading.current_thread() is not threading.main_thread():
        # prevent clutter
        progressbar = False

    if allow_interruption:
        msg += " (hit <ESC> to continue)"

    l_timer = Timer(expiration=timeout)

    with ExitStack() as stack:
        if progressbar:
            from .logging import PROGRESS_BAR
            pr = stack.enter_context(PROGRESS_BAR())
            pr.set_message(msg)

        while True:
            s_timer = Timer()
            ret = pred()
            if ret not in (None, False):
                yield ret
                return
            if l_timer.expired:
                duration = l_timer.stop()
                if throw:
                    raise TimeoutException(message, duration=duration)
                yield None
                return
            yield l_timer.remain
            sleep_for = sleep() if callable(sleep) else sleep
            if allow_interruption:
                from termenu.keyboard import keyboard_listener
                timer = Timer(expiration=sleep_for-s_timer.elapsed)
                for key in keyboard_listener(heartbeat=0.25):
                    if key == "esc":
                        yield None
                        return
                    if key == "enter":
                        break
                    if timer.expired:
                        break
            else:
                s_timeout = max(0, sleep_for-s_timer.elapsed)
                if l_timer.expiration:
                    s_timeout = min(l_timer.remain, s_timeout)
                time.sleep(s_timeout)