File tree Expand file tree Collapse file tree 3 files changed +42
-0
lines changed
prompt_toolkit/application Expand file tree Collapse file tree 3 files changed +42
-0
lines changed Original file line number Diff line number Diff line change
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 (">" )
Original file line number Diff line number Diff line change 2
2
from .current import (
3
3
AppSession ,
4
4
create_app_session ,
5
+ create_app_session_from_tty ,
5
6
get_app ,
6
7
get_app_or_none ,
7
8
get_app_session ,
17
18
"AppSession" ,
18
19
"get_app_session" ,
19
20
"create_app_session" ,
21
+ "create_app_session_from_tty" ,
20
22
"get_app" ,
21
23
"get_app_or_none" ,
22
24
"set_app" ,
Original file line number Diff line number Diff line change 20
20
"get_app_or_none" ,
21
21
"set_app" ,
22
22
"create_app_session" ,
23
+ "create_app_session_from_tty" ,
23
24
]
24
25
25
26
@@ -168,3 +169,29 @@ def create_app_session(
168
169
yield session
169
170
finally :
170
171
_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
You can’t perform that action at this time.
0 commit comments