Main Loop

The MainLoop class ties together a display module, a set of widgets and an event loop. It handles passing input from the display module to the widgets, rendering the widgets and passing the rendered canvas to the display module to be drawn.

You may filter the user’s input before it is passed to the widgets with your own code by using MainLoop.input_filter(), or have special code to handle input not handled by the widgets by using MainLoop.unhandled_input().

You may set alarms to create timed events using MainLoop.set_alarm_at() or MainLoop.set_alarm_in(). These methods automatically add a call to MainLoop.draw_screen() after calling your callback. MainLoop.remove_alarm() may be used to remove alarms.

When the main loop is running, any code that raises an ExitMainLoop exception will cause the loop to exit cleanly. If any other exception reaches the main loop code, it will shut down the screen to avoid leaving the terminal in an unusual state then re-raise the exception for normal handling.

Using MainLoop is highly recommended, but if it does not fit the needs of your application you may choose to use your own code instead. There are no dependencies on MainLoop in other parts of Urwid.

Widgets Displayed

The topmost widget displayed by MainLoop must be passed as the first parameter to the constructor. If you want to change the topmost widget while running, you can assign a new widget to the MainLoop object’s MainLoop.widget attribute. This is useful for applications that have a number of different modes or views.

The displayed widgets will be handling user input, so it is better to extend the widgets that are displayed with your application-specific input handling so that the application’s behaviour changes when the widgets change. If all your custom input handling is done from MainLoop.unhandled_input(), it will be difficult to extend as your application gets more complicated.

Running Another Program in the Terminal

An application can hand the terminal to another program for a while, such as an editor on a temporary file, a pager or a shell, with the MainLoop.paused() context manager:

editor = shlex.split(os.environ.get("EDITOR", "")) or ["vi"]  # "vim -f", "code --wait" carry arguments
with loop.paused():
    subprocess.run([*editor, path], check=False)

The screen is stopped for the block and started again afterwards, with the mouse tracking restored and the whole screen redrawn at the terminal’s current size. The block holds the event loop until it ends, so no input, alarm or watched file is handled while the other program owns the terminal.

Reaching the Running Loop

A widget or a callback finds the loop it runs under with get_running_loop(), instead of being handed the loop by the application:

class Clock(urwid.Text):
    def start(self) -> None:
        urwid.get_running_loop().set_alarm_in(1, self._tick)

    def _tick(self, loop: urwid.MainLoop, _data: object) -> None:
        self.set_text(time.strftime("%H:%M:%S"))
        loop.set_alarm_in(1, self._tick)

get_running_loop() raises RuntimeError when no loop is running; get_running_loop_or_none() returns None instead.

A loop is the running loop:

  • in the thread and the asyncio or Trio task that called MainLoop.run() or MainLoop.start(), until MainLoop.stop();

  • inside every alarm, watched file, watched pipe, input and render call the loop makes, whichever task or context the event loop runs it in;

  • inside MainLoop.draw_screen() and MainLoop.process_input() called by hand, also before the loop is started;

  • in everything that copies one of those contexts: a task made with asyncio.create_task(), asyncio.to_thread(), contextvars.Context.run() on a copy from contextvars.copy_context().

A thread that does not copy the context sees the loop only if its context came from the loop’s thread: a plain threading.Thread and a function submitted to an executor run in the worker thread’s own context, which is empty unless the interpreter gives each new thread a copy of its creator’s context. Capture the loop on the loop’s thread and pass it in, or submit contextvars.copy_context().run(function).

Once MainLoop.stop() ran, no context sees the loop any more, including the ones copied while it was running, and no context keeps it alive. Callbacks the loop registered on an event loop it does not own, such as its watched files on an asyncio loop that goes on running, still refer to it until they are removed. A callback the stopped loop left on an event loop it does not own sees no running loop either.

Being able to find the loop from another thread does not make it safe to use from there: change widgets and the screen only from the thread running the event loop, and hand the work over with MainLoop.call_from_thread(), described below. Explicit arguments remain the way to give a loop to code that runs outside it.

Work From Another Thread

Widgets and the screen belong to the thread running the event loop. A worker thread hands its results to that thread with MainLoop.call_from_thread(), which queues a call and wakes the loop:

def work(loop: urwid.MainLoop) -> None:
    result = slow_computation()
    loop.call_from_thread(status.set_text, f"Result: {result}")

def start(_button: urwid.Button) -> None:
    threading.Thread(target=work, args=(urwid.get_running_loop(),), daemon=True).start()

The loop is captured on the loop’s thread, in the button handler, and passed to the worker, because a plain thread does not see the running loop. The call runs on the loop’s thread like an alarm callback: the screen is redrawn afterwards, ExitMainLoop raised by it stops the loop, and any other exception is logged. Calls run in the order they were made, and a call made after the loop stopped raises RuntimeError. With a screen that has no event loop support, such as the curses screen, a call waits for the next input or alarm unless the loop polls: see Screens Without Event Loop Support. It is safe to call from a signal handler as well.

A worker that produces a stream of small updates, such as the lines of a log, does not make one call per line: each call costs a pass of the event loop. It collects the lines and asks for one drain while none is pending:

lines: collections.deque[str] = collections.deque(maxlen=1000)
drain_pending = threading.Event()

def drain() -> None:
    drain_pending.clear()
    while lines:
        log.body.append(urwid.Text(lines.popleft()))

def on_line(line: str) -> None:  # on the worker thread
    lines.append(line)
    if not drain_pending.is_set():
        drain_pending.set()
        loop.call_from_thread(drain)

examples/thread_worker.py shows a worker reporting its progress and its result.

Event Loops

Urwid’s event loop classes handle waiting for things for the MainLoop. The different event loops allow you to integrate with Asyncio, Trio, Twisted, Glib, Tornado, ZMQ libraries, or use a simple selectors-based loop. Event loop classes abstract the particulars of waiting for input and calling functions as a result of timeouts.

You will typically only have a single event loop in your application, even if you have more than one MainLoop running.

You can add your own files to watch to your event loop, with the watch_file() method. Using this interface gives you the special handling of ExitMainLoop and other exceptions when using Glib, Twisted or Tornado callbacks.

SelectEventLoop

This event loop is based on the selectors module. This is the default event loop created if none is passed to MainLoop.

# same as urwid.MainLoop(widget, event_loop=urwid.SelectEventLoop())
loop = urwid.MainLoop(widget)

AsyncioEventLoop

This event loop integrates with the asyncio module in Python.

evl = urwid.AsyncioEventLoop()  # the running asyncio loop, or a new SelectorEventLoop of its own
loop = urwid.MainLoop(widget, event_loop=evl)

Note

In case of multithreading or multiprocessing usage required, do not use executor directly! Use instead method run_in_executor() of AsyncioEventLoop, which forward API of the same method from asyncio Event Loop run_in_executor. A worker running there hands its results to the widgets with MainLoop.call_from_thread().

Warning

For input handling, selectors based logic is used. Under Windows OS only SelectorEventLoop is supported.

Note

uvloop event loop is not supported officially.

TrioEventLoop

This event loop integrates with Trio. alarm(), watch_file() and enter_idle() also accept an async def callback, which runs as a task in the loop’s nursery.

loop = urwid.MainLoop(widget, event_loop=urwid.TrioEventLoop())

Inside a Trio program that is already running, start the loop with run_async():

async with trio.open_nursery() as nursery:
    event_loop = urwid.TrioEventLoop()
    loop = urwid.MainLoop(widget, event_loop=event_loop)
    with loop.start():
        await event_loop.run_async()
    nursery.cancel_scope.cancel()

Note

run_in_executor() is not supported. Run blocking calls with trio.to_thread.run_sync instead. A worker thread hands its results to the widgets with MainLoop.call_from_thread().

TwistedEventLoop

This event loop uses Twisted’s reactor. It has been set up to emulate SelectEventLoop’s behaviour and will start the reactor and stop it on an error. This is not the standard way of using Twisted’s reactor, so you may need to modify this behaviour for your application.

loop = urwid.MainLoop(widget, event_loop=urwid.TwistedEventLoop())

Note

In case of threading usage required, please use twisted deferToThread method. It supports callbacks if needed. Executors from concurrent.futures are not supported.

GLibEventLoop

Deprecated since version 4.1.7: This API will be removed in version 6.0.

This event loop uses GLib’s event loop. This is useful if you are building an application that depends on DBus events, but don’t want to base your application on Twisted.

loop = urwid.MainLoop(widget, event_loop=urwid.GLibEventLoop())

See also

GLibEventLoop reference

TornadoEventLoop

This event loop integrates with Tornado.

from tornado.ioloop import IOLoop
evl = urwid.TornadoEventLoop(IOLoop())
loop = urwid.MainLoop(widget, event_loop=evl)

Note

In case of multithreading or multiprocessing usage required, do not use executor directly! Use instead method run_in_executor() of TornadoEventLoop, which forward API of the same method from tornado.ioloop.IOLoop (and internally use asyncio run_in_executor). A worker running there hands its results to the widgets with MainLoop.call_from_thread().

ZMQEventLoop

This event loop integrates with 0MQ.

evl = urwid.ZMQEventLoop()
loop = urwid.MainLoop(widget, event_loop=evl)