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

I have a script

a = input("Enter something: ")
print(f"You entered: {a}")

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

Enter something: y
You entered: y

If I run yes | ./

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


Thank you very much!

1 Like