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 an unexpected output like this, I process it by redirecting stdout/stderr 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 actually suppressed, but not escape char.

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

So here are my two questions:

  • How is it possible for this escape character to pass?
  • How to suppress it?
+8
python import readline stdout io-redirection
source share
3 answers

this is what I use (admittedly, based on @jypeter's answer), clearing the TERM environment variable only if the output does not go into tty (for example, redirects 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 
+1
source share

To answer the first question: changing sys.stdout does not actually affect the file; the file descriptor stdout points to , but instead just what high-level Python file object is considered stdout. On the other hand, changing sys.stdout affects your Python code, but not (in general) any compiled extensions you can use (for example, the readline module). All this applies to sys.stderr .

To answer the second: you can do what this answer offers (which should be easy to port to Python). Although the suggestions in the comments sound like the best way to go.

0
source share

I used the following hack before importing readline

 import os if os.environ['TERM'] == 'xterm': os.environ['TERM'] = 'vt100' # Now it OK to import readline :) import readline 
0
source share

All Articles