How to have consistent spacing with piping the "yes" command into a script vs manually entering "y"

I have a script input.py:

#!/bin/python
a = input("Enter something: ")
print(f"You entered: {a}")

If I run ./input.py from the terminal and manually enter “y”, the output is:

Enter something: y
You entered: y

If I run yes | ./input.py:

Enter something: You entered: y

The former has a two-line output, the latter has one line. I’m writing a program where this kind of spacing is important. Is there any way to make the spacing consistent for both input modes?

Yes, you can! It depends a bit on how many edge cases you want to deal with, like raw mode, no-echo mode, and so on, but if all you’re worried about is input redirection, that’s easy to check for!

import sys
if not sys.stdin.isatty():
    _input = input
    def input(prompt=''):
        ret = _input(prompt)
        print(ret)
        return ret

# Proceed as before
a = input("Enter something: ")
print(f"You entered: {a}")

The key here is the isatty() method, which tells you whether you’re connected to a TTY (a typical console) or to a pipe. When you’re not connected to a TTY, the default effect of echoing the input is then recreated.

You MAY want to handle other cases like “echo has been disabled” (eg for password input), but if this is all you need, a simple check should suffice.

2 Likes

Thank you very much!

1 Like