Is it possible to combine piped input and TTY prompts in Python CLI scripts? E.g., running this:
import sys
piped_text = None
if not sys.stdin.isatty():
piped_text = sys.stdin.read()
user_in = raw_input('Enter something: ')
if piped_text:
sys.stdout.write(piped_text)
sys.stdout.write(user_in + '\n')
Produces the following output:
~: python mrprompt.py
Enter something: something
something
~: echo foo | python mrprompt.py
Enter something: Traceback (most recent call last):
File "mrprompt.py", line 9, in <module>
user_in = raw_input('Enter something: ')
EOFError: EOF when reading a line
When the output I’m looking for is this:
~: python mrprompt.py
Enter something: something
something
~: echo foo | python mrprompt.py
Enter something: something
foo
something
I guess, worded differently, is it possible for a subshell to know the tty of its parent shell? Is it possible, in Python, to interact a parent shell’s tty? I use bash inside of GNU Screen (therefore, reading the ‘SSH_TTY’ environment variable is not a viable option).
This works, more or less:
Save as
foo.pyand tryecho goodbye | ./foo.pyOf course,
/dev/ttyonly exists on Unix. And if you run it in a process with no controlling terminal, theopen()will probably fail…