prompt-toolkit / python-prompt-toolkit

Library for building powerful interactive command line applications in Python
https://python-prompt-toolkit.readthedocs.io/
BSD 3-Clause "New" or "Revised" License
9.29k stars 715 forks source link

run as background process, connect to active terminal session #1087

Open tcrensink opened 4 years ago

tcrensink commented 4 years ago

I want to create an TUI that runs in the background but connects to an active terminal session on command. Is this possible?

I have an app that uses prompt_toolkit, that runs with python app.py; after (slow) initial startup it is quite responsive. Is is possible to keep it running in the background and connect to the tty of a terminal session, to avoid the delay of quitting/restarting the process?

jonathanslenders commented 4 years ago

Hi @tcrensink,

I assume you are looking for a way to detach the process from the TTY, like tmux, screen and others. You can have a look at pymux, which does it, but honestly the code is not reusable, and pretty complex. (And I'm not 100% sure how stable it is on the latest prompt_toolkit version.)

The idea is to provide a custom Output class that you pass to the prompt_toolkit Application. This shouldn't write to stdout, but to a pipe. The the actual program running in the TTY is one that connects to the prompt_toolkit application over a unix socket. The render output is passed over the socket and written to the TTY. The server side of this piece will actually listen on the unix socket, and create new prompt_toolkit Application classes for each incoming connection. There's probably a bit more to take into account, like handling terminal resize events, double forking the server the first time the client starts, the implementation of the Input class and so on.

tcrensink commented 4 years ago

@jonathanslenders thank you for the thorough response. You are correct: I'd like to mimic the behavior of tmux/screen for fast attaching/detaching to a running prompt-toolkit process.

For clarity: are you suggesting that this could be implemented as it is done in pymux using prompt-toolkit only (and of course required os resources)? Any links in pymux for where the process you describe above happens would be helpful.

karandwivedi42 commented 2 years ago

I'd like to mimic the behavior of tmux/screen for fast attaching/detaching to a running prompt-toolkit process.

@tcrensink did you find a solution for this?

tcrensink commented 2 years ago

@karandwivedi42, I found a hack that works ok. I ran the prompt_toolkit process in a Docker container, then connect/disconnect to the container with keybindings, while leaving the prompt_toolkit process running. The command to conntect/disconnect (and then clear the terminal window) looks something like this:

docker attach my_prompt_toolkit_container --detach-keys="ctrl-c"; printf "\033c"

I renamed the above command my_app for convenience; this is not what I would call a production quality solution