3

I have a Python script that needs to suppress the echo of stdin that happens when you use the keyboard to respond to a prompt.

When using the keyboard, I can use VT100 control codes to move up one line, clear the line, and then move up another line (so that the output clears the newly-blanked line).

However, this code messes up the output and ends up clearing a line of valid output when the input comes from a file (ie, cat test | myscript.py, because stdin does not apparently echo anything to stdout in this case.

I can't control how the input is sent to the script, and I don't know whether the user will use the keyboard or files.

Is there any way for me to check the output of raw_input() and only run the VT100 control codes if the input came from the keyboard?

2 Answers 2

7

The function that you want is isatty ("is a TTY") on filehandles. You can test it on sys.stdin, sys.stdout or sys.stderr as you need.

>>> import sys
>>> sys.stdin.isatty()
True

Incidentally, that is what Python is doing too to detect whether or not to show the interactive prompt (just try cat | python)

Sign up to request clarification or add additional context in comments.

2 Comments

Just out of curiosity, is there any way to "script" TTY input that might throw a wrench into my script?
yes there is but it does not work through pipe. See the pty module. If your purpose is to just disable echo altogether, do as Ignacio says, (after testing for isatty); that is what shells and editors use anyway.
1

"... suppress the echo of stdin ..."

Here’s a function that prompts for a password with echoing turned off...

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.