Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python readline module prints escape character during import

I am using the readline module with Python 2.7.3 with Fedora 17. I do not have this problem with Ubuntu 12.10.

During import readline, an escape char is displayed.

$ python -c 'import readline' |less
ESC[?1034h(END)

Usually when I get unexpected output like this, I handle it using stdout/stderr redirection to a dummy file descriptor (example below). But this time, this method does not work.

import sys

class DummyOutput(object):
    def write(self, string):
        pass

class suppress_output(object):
    """Context suppressing stdout/stderr output.
    """
    def __init__(self):
        pass
    def __enter__(self):
        sys.stdout = DummyOutput()
        sys.stderr = DummyOutput()
    def __exit__(self, *_):
        sys.stdout = sys.__stdout__
        sys.stderr = sys.__stderr__

if __name__ == '__main__':
    print 'Begin'
    with suppress_output():
        # Those two print statements have no effect
        # but *import readline* prints an escape char
        print 'Before importing'
        import readline
        print 'After importing'
    # This one will be displayed
    print 'End'

If you run this snippet in a test.py script, you will see that inside the suppress_output context, the print statements are indeed suppressed, but not the escape char.

$ python test.py |less
Begin
ESC[?1034hEnd
(END)

So here are my two questions:

  1. How is it possible for this escape character to get through?
  2. How to suppress it?
like image 728
Alex Avatar asked Apr 02 '13 09:04

Alex


1 Answers

here is what I'm using (admittedly based on @jypeter 's answer), clearing the TERM environment variable only if the output does not go to a tty (e.g. is being redirected to a file):

if not sys.stdout.isatty():

    # remember the original setting
    oldTerm = os.environ['TERM']

    os.environ['TERM'] = ''

    import readline

    # restore the orignal TERM setting
    os.environ['TERM'] = oldTerm

    del oldTerm
like image 167
Andre Holzner Avatar answered Nov 15 '22 01:11

Andre Holzner