if STREAM.isatty():

Chris Angelico rosuav at gmail.com
Fri Aug 30 03:53:02 EDT 2019


On Fri, Aug 30, 2019 at 5:51 PM Hongyi Zhao <hongyi.zhao at gmail.com> wrote:
>
> On Fri, 30 Aug 2019 01:29:48 +0200, Peter Otten wrote:
>
> > Perhaps a simple example can help?
> >
> > $ cat checktty.py import sys
> >
> > stream = sys.stdout
> >
> > if stream.isatty():
> >     message = "tty"
> > else:
> >     message = "no tty"
> > print(message, file=stream)
> >
> > When you run the script it prints to the terminal:
> >
> > $ python3 checktty.py tty
> >
> > But when you redirect to a pipe or into a file:
> >
> > $ python3 checktty.py | cat no tty
> >
> > $ python3 checktty.py > tmp.txt $ cat tmp.txt no tty
>
>
> But, see my example:
>
> $ cat check-isatty.py
> import sys
> import time
>
> if sys.stderr.isatty():
>         p = 'tty ' + '\r'
> else:
>         p = 'no tty ' + '\n'
>
> sys.stderr.write(p)
> sys.stderr.flush()
> time.sleep(1.0)
>
>
> I run both of the following commands:
>
> $ python check-isatty.py
> $ python check-isatty.py | cat
>
> Both will output `tty'.  So still I cannot figure out the issue.
>

That's because sys.stderr is never changing in your example here. Try
checking whether sys.stdout is a TTY instead.

(Also, why the sleep? Seems unnecessary.)

ChrisA



More information about the Python-list mailing list