In Python code, I frequently send commands to the shell and read the response using
import subprocess as S
x = subprocess.Popen('<command>', shell=True, stdout=S.PIPE)
x.stdout.read()
, where <command> is the shell command in question. However, I find that when this instruction is issued in a subprocess, for a command stty size, for example, the shell responds with
stty: stdin isn't a terminal
and my instruction returns an empty string. Following the Python docs at http://docs.python.org/library/subprocess#popen-objects , I have also tried replacing stdout.read() with communicate():
x = subprocess.Popen('<command>', shell=True, stdin=S.PIP, stdout=S.PIPE)
x.stdout.read()
but the shell still responds the same way.
My question: How can I make Python treat standard input as a terminal?
It’s not that Python isn’t treating stdin like a terminal; if stdin is a terminal, Python is likely treating it as such. But the subprocess’s stdin may not be. In the second case, it definitely isn’t a terminal, since you are explicitly using a pipe instead.
You probably won’t be able to make stty treat a pipe as a terminal, short of changing the way it works. But that probably isn’t what you want to do, anyway.
Your first example, though, should work if Python’s own stdin is a tty, since stty should inherit that from the shell.
Perhaps I’m unclear on what you meant by “when this instruction is issued in a subprocess”. Technically, everything on a Un*x system except for init/launchd is a subprocess.