Skip to content

Commit 7dd8435

Browse files
Added create_app_session_from_tty.
A utility to quickly set up input/output attached to the TTY.
1 parent 2c96fe2 commit 7dd8435

File tree

3 files changed

+42
-0
lines changed

3 files changed

+42
-0
lines changed
Lines changed: 13 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,13 @@
1+
#!/usr/bin/env python
2+
"""
3+
This will display a prompt that will always use the terminal for input and
4+
output, even if sys.stdin/stdout are connected to pipes.
5+
6+
For testing, run as:
7+
cat /dev/null | python ./enforce-tty-input-output.py > /dev/null
8+
"""
9+
from prompt_toolkit.application import create_app_session_from_tty
10+
from prompt_toolkit.shortcuts import prompt
11+
12+
with create_app_session_from_tty():
13+
prompt(">")

prompt_toolkit/application/__init__.py

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -2,6 +2,7 @@
22
from .current import (
33
AppSession,
44
create_app_session,
5+
create_app_session_from_tty,
56
get_app,
67
get_app_or_none,
78
get_app_session,
@@ -17,6 +18,7 @@
1718
"AppSession",
1819
"get_app_session",
1920
"create_app_session",
21+
"create_app_session_from_tty",
2022
"get_app",
2123
"get_app_or_none",
2224
"set_app",

prompt_toolkit/application/current.py

Lines changed: 27 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -20,6 +20,7 @@
2020
"get_app_or_none",
2121
"set_app",
2222
"create_app_session",
23+
"create_app_session_from_tty",
2324
]
2425

2526

@@ -168,3 +169,29 @@ def create_app_session(
168169
yield session
169170
finally:
170171
_current_app_session.reset(token)
172+
173+
174+
@contextmanager
175+
def create_app_session_from_tty() -> Generator[AppSession, None, None]:
176+
"""
177+
Create `AppSession` that always prefers the TTY input/output.
178+
179+
Even if `sys.stdin` and `sys.stdout` are connected to input/output pipes,
180+
this will still use the terminal for interaction (because `sys.stderr` is
181+
still connected to the terminal).
182+
183+
Usage::
184+
185+
from prompt_toolkit.shortcuts import prompt
186+
187+
with create_app_session_from_tty():
188+
prompt('>')
189+
"""
190+
from prompt_toolkit.input.defaults import create_input
191+
from prompt_toolkit.output.defaults import create_output
192+
193+
input = create_input(always_prefer_tty=True)
194+
output = create_output(always_prefer_tty=True)
195+
196+
with create_app_session(input=input, output=output) as app_session:
197+
yield app_session

0 commit comments

Comments
 (0)