Pipes and tooltips in Python CLI scripts

Is it possible to combine incoming requests and TTY requests in Python CLI scripts? For example, do the following:

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')  

It 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 the following:

~: python mrprompt.py
Enter something: something
something
~: echo foo | python mrprompt.py
Enter something: something
foo
something

I suppose, in other words, is it possible for a subshell to know the tty of its parent shell? Is it possible in Python to interact with the tty parent shell? I use bash inside the GNU screen (so reading the environment variable "SSH_TTY" is not a viable option).

+5
source share
3 answers

This works, more or less:

#!/usr/bin/python

import sys

saved_stdin = sys.stdin
sys.stdin = open('/dev/tty', 'r')
result = raw_input('Enter something: ')
sys.stdout.write('Got: ' + result + '\n')
sys.stdin = saved_stdin
result2 = sys.stdin.read()
sys.stdout.write('Also got: ' + result2)

Save as foo.pyand tryecho goodbye | ./foo.py

, /dev/tty Unix. , open(), , ...

+6

, stdin , sys.stdin.isatty. EOF, stdin.read(), raw_input().

, , - , - . , stdin raw_input . stdin , .

, script

--input=file.txt

.

+5

, .

- subprocess. Python. / .

. . .

. . . . Windows CMD.EXE/COMMAND.COM . - - , DOS/Windows .

, mysql . Linux (, , Mac OS X), , , Nemo. , Windows, . ( Windows - wconio. http://newcenturycomputers.net/projects/wconio.html)

, . -: stdin, stdout stderr. stderr, stdout .

+1

All Articles