Python urwid.ExitMainLoop() Examples

The following are 30 code examples of urwid.ExitMainLoop(). You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may also want to check out all available functions/classes of the module urwid , or try the search function .
Example #1
Source File: ui.py    From yTermPlayer with GNU General Public License v3.0 6 votes vote down vote up
def handle_keys(self,key):
        if(key=='q'):
            raise urwid.ExitMainLoop()
        key_dict={
        'n':self.player_object.play_next,
        'p':self.player_object.play_prev,
        'h':self.player_object.play_first,
        'e':self.player_object.play_last,
        ' ':self.toggle_playing,
        's':self.save_list,
        '1': self.change_play_mode_to_repeat_one,
        '2': self.change_play_mode_to_repeat_list,
        '3': self.change_play_mode_to_repeat_off,
        'r': self.change_play_mode_to_random,
        'u': self.volume_up,
        'd': self.volume_down,
        }
        try:
            key_dict[key]()
        except:
            pass 
Example #2
Source File: test_event_loops.py    From anyMesh-Python with MIT License 6 votes vote down vote up
def test_run(self):
            evl = self.evl
            out = []
            rd, wr = os.pipe()
            self.assertEqual(os.write(wr, "data".encode('ascii')), 4)
            def step2():
                out.append(os.read(rd, 2).decode('ascii'))
            def say_hello():
                out.append("hello")
            def say_waiting():
                out.append("waiting")
            def exit_clean():
                out.append("clean exit")
                raise urwid.ExitMainLoop
            def exit_error():
                1/0
            handle = evl.watch_file(rd, step2)
            handle = evl.alarm(0.01, exit_clean)
            handle = evl.alarm(0.005, say_hello)
            self.assertEqual(evl.enter_idle(say_waiting), 1)
            evl.run()
            self.assertIn("da", out)
            self.assertIn("ta", out)
            self.assertIn("hello", out)
            self.assertIn("clean exit", out) 
Example #3
Source File: demo.py    From anyMesh-Python with MIT License 6 votes vote down vote up
def keypress(self, size, key):
        key = super(SetupListBox, self).keypress(size, key)
        if key == 'enter':
            if self.focus_position > 2 and len(self.body[self.focus_position].edit_text) == 0:
                device_name = self.body[2].edit_text
                device_listens = []
                for index, item in enumerate(self.body):
                    if index > 2:
                        device_listens.append(item.edit_text)
                start_anymesh(device_name, device_listens)
                load_msg_frame()

            else:
                self.body.insert(self.focus_position + 1, urwid.Edit("Enter a keyword to listen to: "))
                self.focus_position += 1
        elif key == 'esc':
            raise urwid.ExitMainLoop() 
Example #4
Source File: main.py    From Discurses with MIT License 5 votes vote down vote up
def quit(widget, size, key):
        logger.info('User quit')
        widget.urwid_loop.stop()
        widget.discord_loop.stop()
        raise urwid.ExitMainLoop() 
Example #5
Source File: sncli.py    From sncli with MIT License 5 votes vote down vote up
def gui_stop(self):
        # don't exit if there are any notes not yet saved to the disk

        # NOTE: this was originally causing hangs on exit with urllib2
        # should not be a problem now since using the requests library
        # ref https://github.com/insanum/sncli/issues/18#issuecomment-105517773
        if self.ndb.verify_all_saved():
            # clear the screen and exit the urwid run loop
            self.gui_clear()
            raise urwid.ExitMainLoop()
        else:
            self.log(u'WARNING: Not all notes saved to disk (wait for sync worker)') 
Example #6
Source File: urwidpatches.py    From stig with GNU General Public License v3.0 5 votes vote down vote up
def _exception_handler(self, loop, context):
        exc = context.get('exception')
        if exc:
            loop.stop()
            if not isinstance(exc, urwid.ExitMainLoop):
                self._exc_info = exc
        else:
            loop.default_exception_handler(context) 
Example #7
Source File: view.py    From binch with MIT License 5 votes vote down vote up
def unhandled_input(self, k):
        def goto(text):
            try:
                if bool(re.match(r'^([0-9]|0x[0-9a-fA-F]+|\+|\-| )+$',text)):
                    address = eval(text)
                else:
                    return "It is invalid number: "+text
            except:
                return "Fail to calculate address: "+text

            if address in self.index_map:
                self.history.append(self.disasmlist._w.body[self.disasmlist._w.focus_position].instruction.address)
                self.disasmlist.set_focus(self.index_map[address])
                return "Jump to "+hex(address)
            else:
                for i in range(1, 0x10):
                    if address - i in self.index_map:
                        self.history.append(self.disasmlist._w.body[self.disasmlist._w.focus_position].instruction.address)
                        self.disasmlist.set_focus(self.index_map[address - i])
                        return "Jump to "+hex(address - i)
                    elif address + i in self.index_map:
                        self.history.append(self.disasmlist._w.body[self.disasmlist._w.focus_position].instruction.address)
                        self.disasmlist.set_focus(self.index_map[address + i])
                        return "Jump to "+hex(address + i)

                return "Invalid address: "+hex(address)

        if k in ('q', 'Q'):
            def ask_quit(yn, arg):
                if yn == 'y':
                    raise urwid.ExitMainLoop()
            signals.set_prompt_yn.send(self, text="Quit?", callback=ask_quit, arg=None)
        elif k in ('g', 'G'):
            signals.set_prompt.send(self, text="Goto: ", callback=goto)
        elif k in ('s', 'S'):
            self.disasmblr.save()
        elif k == "esc":
            if len(self.history) > 0:
                address = self.history[-1]
                del self.history[-1]
                self.disasmlist.set_focus(self.index_map[address]) 
Example #8
Source File: redial.py    From redial with GNU General Public License v3.0 5 votes vote down vote up
def close_dialog_and_run(self, command=None):
        if command is not None:
            self.command = command
            self.loop.widget = self.view
            raise urwid.ExitMainLoop()
        else:
            self.loop.widget = self.view 
Example #9
Source File: redial.py    From redial with GNU General Public License v3.0 5 votes vote down vote up
def sigint_handler(app, signum, frame):
    app.command = EXIT_REDIAL
    raise urwid.ExitMainLoop() 
Example #10
Source File: ui.py    From yTermPlayer with GNU General Public License v3.0 5 votes vote down vote up
def keypress(self, size, key):
        global LIST_LOCK #CAN't FIND ANY OTHER WAY THAN THIS TO CHANGE THE VARIABLES OF MY player_ui CLASS
        if(key=='enter'):
            LIST_LOCK = False
        elif(key == 'q'):
            raise urwid.ExitMainLoop()
        return key 
Example #11
Source File: clients.py    From wsstat with MIT License 5 votes vote down vote up
def update_urwid(self):
        interval = .1
        status_line = "{hostname} | Connections: [{current}/{total}] | Total Messages: {message_count} | Messages/Second: {msgs_per_second}/s"

        while True:
            if self._exiting:
                return True
                #raise urwid.ExitMainLoop

            # Only update things a max of 10 times/second
            yield from asyncio.sleep(interval)

            # Get the current global message count
            global_message_count = int(repr(self.global_message_counter)[6:-1])
            self.ring_buffer.append(global_message_count)

            currently_connected_sockets = len([x for x in self.sockets.values() if x and not isinstance(x, BaseException) and x.ws.state == State.OPEN])

            self.logger.update_graph_data([self.messages_per_second,])

            # Get and update our blinkboard widget
            self.blinkboard.generate_blinkers(self.sockets)
            # Make the status message
            status_message = status_line.format(
                hostname=self.websocket_url.netloc,
                current=currently_connected_sockets,
                total=self.total_connections,
                message_count=global_message_count,
                msgs_per_second=self.messages_per_second
            )
            self.frame.footer.set_text(status_message) 
Example #12
Source File: gui.py    From TWchat with MIT License 5 votes vote down vote up
def exit_on_alt_q(key):
    if key in (u'œ',u'Œ'):
        raise urwid.ExitMainLoop() 
Example #13
Source File: visualizer.py    From gtui with GNU General Public License v3.0 5 votes vote down vote up
def handle_input(self, key):
        if key == 'j':
            self.set_selected_tab(min(self.max_index, self.selected_index + 1))
            self.refresh_main_display()
            self.refresh_tab_display()

        if key == 'k':
            self.set_selected_tab(max(self.min_index, self.selected_index - 1))
            self.refresh_main_display()
            self.refresh_tab_display()

        if key == 'tab':
            self.get_selected_tab().toggle_focus()
            self.refresh_main_display()

        if key == 'q':
            raise urwid.ExitMainLoop()

        if key == 'y':
            output = self.get_selected_tab().text
            pyperclip.copy(output)

        if key == 't':
            logger.debug('%s : Toggle Text Follow Mode', key)
            self.should_follow_txt = not self.should_follow_txt
            self.refresh_footer_display()

        if key in ['h', 'l', 'up', 'down']:
            logger.debug('%s : Toggle Text Follow Mode', key)
            self.should_follow_txt = False
            self.refresh_footer_display() 
Example #14
Source File: visualizer.py    From gtui with GNU General Public License v3.0 5 votes vote down vote up
def refresh_ui_every_half_second(self, loop=None, data=None):
        self.refresh_ui()

        if self.need_exit:
            raise urwid.ExitMainLoop()

        self.loop.set_alarm_in(0.5, self.refresh_ui_every_half_second) 
Example #15
Source File: tui.py    From stig with GNU General Public License v3.0 5 votes vote down vote up
def run(self):
        import urwid
        raise urwid.ExitMainLoop() 
Example #16
Source File: demo.py    From anyMesh-Python with MIT License 5 votes vote down vote up
def handle_input(key):
    if key == 'esc':
        raise urwid.ExitMainLoop() 
Example #17
Source File: test_event_loops.py    From anyMesh-Python with MIT License 5 votes vote down vote up
def test_event_loop(self):
        rd, wr = os.pipe()
        evl = self.evl
        out = []
        def step1():
            out.append("writing")
            os.write(wr, "hi".encode('ascii'))
        def step2():
            out.append(os.read(rd, 2).decode('ascii'))
            raise urwid.ExitMainLoop
        handle = evl.alarm(0, step1)
        handle = evl.watch_file(rd, step2)
        evl.run()
        self.assertEqual(out, ["writing", "hi"]) 
Example #18
Source File: test_event_loops.py    From anyMesh-Python with MIT License 5 votes vote down vote up
def test_run(self):
        evl = self.evl
        out = []
        rd, wr = os.pipe()
        self.assertEqual(os.write(wr, "data".encode('ascii')), 4)
        def say_hello():
            out.append("hello")
        def say_waiting():
            out.append("waiting")
        def exit_clean():
            out.append("clean exit")
            raise urwid.ExitMainLoop
        def exit_error():
            1/0
        handle = evl.alarm(0.01, exit_clean)
        handle = evl.alarm(0.005, say_hello)
        self.assertEqual(evl.enter_idle(say_waiting), 1)
        evl.run()
        self.assertIn("hello", out)
        self.assertIn("clean exit", out)
        handle = evl.watch_file(rd, exit_clean)
        del out[:]
        evl.run()
        self.assertEqual(out, ["clean exit"])
        self.assertTrue(evl.remove_watch_file(handle))
        handle = evl.alarm(0, exit_error)
        self.assertRaises(ZeroDivisionError, evl.run)
        handle = evl.watch_file(rd, exit_error)
        self.assertRaises(ZeroDivisionError, evl.run) 
Example #19
Source File: app.py    From toot with GNU General Public License v3.0 5 votes vote down vote up
def build_timeline(self, name, statuses, local):
        def _close(*args):
            raise urwid.ExitMainLoop()

        def _next(*args):
            self.async_load_timeline(is_initial=False)

        def _thread(timeline, status):
            self.show_thread(status)

        def _toggle_save(timeline, status):
            if not timeline.name.startswith("#"):
                return
            hashtag = timeline.name[1:]
            assert isinstance(local, bool), local
            timelines = self.config.setdefault("timelines", {})
            if hashtag in timelines:
                del timelines[hashtag]
                self.footer.set_message("#{} unpinned".format(hashtag))
            else:
                timelines[hashtag] = {"local": local}
                self.footer.set_message("#{} pinned".format(hashtag))
            self.loop.set_alarm_in(5, lambda *args: self.footer.clear_message())
            config.save_config(self.config)

        timeline = Timeline(name, statuses)

        self.connect_default_timeline_signals(timeline)
        urwid.connect_signal(timeline, "next", _next)
        urwid.connect_signal(timeline, "close", _close)
        urwid.connect_signal(timeline, "thread", _thread)
        urwid.connect_signal(timeline, "save", _toggle_save)

        return timeline 
Example #20
Source File: app.py    From toot with GNU General Public License v3.0 5 votes vote down vote up
def unhandled_input(self, key):
        # TODO: this should not be in unhandled input
        if key in ('e', 'E'):
            if self.exception:
                self.show_exception(self.exception)

        elif key in ('g', 'G'):
            if not self.overlay:
                self.show_goto_menu()

        elif key in ('h', 'H'):
            if not self.overlay:
                self.show_help()

        elif key == 'esc':
            if self.overlay:
                self.close_overlay()
            elif self.timeline.name != "home":
                # similar to goto_home_timeline() but without handling overlay (absent here)
                self.timeline_generator = api.home_timeline_generator(
                    self.app, self.user, limit=40)
                self.async_load_timeline(is_initial=True, timeline_name="home")

        elif key in ('q', 'Q'):
            if self.overlay:
                self.close_overlay()
            else:
                raise urwid.ExitMainLoop() 
Example #21
Source File: app.py    From usolitaire with MIT License 5 votes vote down vote up
def exit_on_q(key):
    if key in ('q', 'Q', 'esc'):
        raise urwid.ExitMainLoop() 
Example #22
Source File: browse.py    From zstack-utility with Apache License 2.0 5 votes vote down vote up
def unhandled_input(self, k):
        # update display of focus directory
        if k in ('q','Q'):
            raise urwid.ExitMainLoop() 
Example #23
Source File: setting.py    From zstack-utility with Apache License 2.0 5 votes vote down vote up
def _unhandled_input(self, k):
        if k in ('q', 'Q'):
            raise urwid.ExitMainLoop() 
Example #24
Source File: test.py    From zstack-utility with Apache License 2.0 5 votes vote down vote up
def unhandled_input(self, k):
        if k in ['q', 'Q']:
            raise urwid.ExitMainLoop() 
Example #25
Source File: main.py    From pycopia with Apache License 2.0 5 votes vote down vote up
def _popform(self, form, pkval):
        if form is not None:
            urwid.disconnect_signal(form, 'pushform', self._pushform)
            urwid.disconnect_signal(form, 'popform', self._popform)
            urwid.disconnect_signal(form, 'message', self._message)
        if self._formtrail:
            self.form = self._formtrail.pop()
            self.form.invalidate()
            self.top.body = self.form
        else:
            raise urwid.ExitMainLoop() 
Example #26
Source File: main.py    From wikicurses with MIT License 5 votes vote down vote up
def processCmd(cmd, *args):
    global current

    if cmd in ('q', 'quit'):
        raise urwid.ExitMainLoop
    elif cmd == 'bmark':
        wiki.bmarks.add(page.title)
        ex.notify("Bookmark Added")
    elif cmd in overlaymap:
        openOverlay(overlaymap[cmd]())
    elif cmd == 'open':
        if args:
            openPage(' '.join(args))
        else:
            openOverlay(SearchBox())
    elif cmd == 'clearcache':
        wiki.clear_cache()
    elif cmd == 'edit':
        edit(page.title)
    elif cmd == 'help':
        executeCommand(['man', 'wikicurses'])
    elif cmd == 'back':
        if current > 0:
            current -= 1
            openPage(history[current], browsinghistory=True)
    elif cmd == 'forward':
        if current < len(history)-1:
            current += 1
            openPage(history[current], browsinghistory=True)
    elif cmd == 'random':
        openPage(wiki.random())
    elif cmd:
        ex.notify(cmd + ': Unknown Command') 
Example #27
Source File: gazua.py    From ec2-gazua with MIT License 5 votes vote down vote up
def key_pressed(key):
    if key == 'esc':
        raise urwid.ExitMainLoop() 
Example #28
Source File: events.py    From conjure-up with MIT License 5 votes vote down vote up
def handle_exception(loop, context):
    exc = context.get('exception')
    if exc is None or isinstance(exc, CancelledError):
        return  # not an error, cleanup message
    if isinstance(exc, ExitMainLoop):
        Shutdown.set()  # use previously stored exit code
        return
    if Error.is_set():
        return  # already reporting an error
    Error.set()
    exc_info = (type(exc), exc, exc.__traceback__)

    if any(pred(exc) for pred in NOTRACK_EXCEPTIONS):
        app.log.debug('Would not track exception: {}'.format(exc))
    if not (app.no_report or any(pred(exc) for pred in NOTRACK_EXCEPTIONS)):
        track_exception(str(exc))
        utils.sentry_report(exc_info=exc_info)

    msg = 'Unhandled exception'
    if 'future' in context:
        msg += ' in {}'.format(context['future'])
    app.log.exception(msg, exc_info=exc)

    if app.headless:
        msg = str(exc)
        utils.error(msg)
        Shutdown.set(1)
    else:
        app.exit_code = 1  # store exit code for later
        app.ui.show_exception_message(exc)  # eventually raises ExitMainLoop 
Example #29
Source File: base.py    From conjure-up with MIT License 5 votes vote down vote up
def show(self):
        def _stop(key):
            if key in ['q', 'Q']:
                raise ExitMainLoop()

        app.no_track = True
        app.no_report = True
        app.ui = ConjureUI()
        EventLoop.build_loop(app.ui, STYLES, unhandled_input=_stop)
        super().show()
        EventLoop.run() 
Example #30
Source File: command.py    From screeps_console with MIT License 5 votes vote down vote up
def exit(self, comp):
        raise urwid.ExitMainLoop()