Skip to content

Gracefully handle termination signals #5140

Open
@davidfokkema

Description

@davidfokkema

On macOS, and presumably similarly on *nix, you can do this:

import pathlib
import signal
import time

from textual.app import App, ComposeResult
from textual.widgets import Placeholder


class MinimalApp(App[None]):
    _signal = None

    def on_mount(self) -> None:
        signal.signal(signalnum=signal.SIGHUP, handler=self.catch_signal)
        signal.signal(signalnum=signal.SIGTERM, handler=self.catch_signal)

    def compose(self) -> ComposeResult:
        yield Placeholder("This is a minimal app.")

    def catch_signal(self, signum, frame) -> None:
        self._signal = signum
        self.exit()


app = MinimalApp()
app.run()

pathlib.Path("signal.txt").write_text(
    f"{time.monotonic()}: Received signal: {app._signal}"
)
print("Done")
print(f"Received signal: {app._signal}")

This will gracefully shutdown the app when the app is killed (with SIGTERM) or when the terminal is closed (sending a SIGHUP to child processes). Currently, in the case of SIGTERM, Textual does shutdown, but not gracefully and stdin/stdout are messed up. Default signal handlers would improve that.

On Windows, it might be a bit more difficult (maybe this would work: https://stackoverflow.com/questions/69323194/how-do-i-handle-windows-terminal-closing-event-in-python) and even on Linux there are reports it might be not as straightforward as hoped. Still, might be worth it?

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions