Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to convince python stream objects to return true from isatty()?

Tags:

python

Usually isatty() tells you if a stream is a TTY and is the common way to determine if the stdout or stderr is a console.

The problem is that when you run a script under a IDE the output is redirected so istty will return False or will not even be defined.

I want to add this attribute to the sys.stdout or even sys.__stdout__ in order to change the behaviour of the library that was checkign for tty.

Still I would like to do this without having to replace the object itself with a proxy, if possible.

# some logic...
setattr(sys.stdout, 'isatty', True)
>> AttributeError: 'file' object attribute 'isatty' is read-only
like image 749
sorin Avatar asked Aug 31 '25 04:08

sorin


1 Answers

Use a proxy object. No solution that I can think of is easier than that.

class PseudoTTY(object):
    def __init__(self, underlying):
        self.__underlying = underlying
    def __getattr__(self, name):
        return getattr(self.__underlying, name)
    def isatty(self):
        return True

sys.stdin = PseudoTTY(sys.stdin)

(The other solution would involve ptys.)

like image 85
Fred Foo Avatar answered Sep 02 '25 16:09

Fred Foo