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