A python module I am using provides a hook that allows capturing user keyboard input before it is sent to a shell terminal. The problem I am facing is that it captures input character-by-character, which makes capturing the input commands difficult when the user performs such things as backspacing or moving the cursor.

For example, given the string exit\x1b[4D\x1b[Jshow myself out, the following takes place:

>>> a = exit\x1b[4D\x1b[Jshow myself out
>>> print(a)
show myself out

>>> with open('file.txt', 'w+') as f:
>>>     f.write(a)
>>> exit()
less abc.txt

The less command shows the raw command (exit\x1b[4D\x1b[Jshow myself out), when in fact I would like it to be stored 'cleanly' as it is displayed when using the print function (show myself out).

Printing the result, or 'cat'ing the file shows exactly what I would want to be displayed, but I am guessing here that the terminal is transforming the output.

Based on my question on Stack Overflow, I have determined that the best solution is to use a third party tool or utility in order to generate a string using the character-by-character input.

So far I have stumbled upon ansiterm, which seems to solve this exact problem, though it may not be as robust as other utilities with this same purpose. Has anyone come across any other tool that can help with this problem?


Note that the terminal is not preprocessing the output in any way. These escape sequences are moving the cursor and overwriting the word "exit".

$ echo -e 'exit\x1b[4D\x1b[Jshow myself out'
show myself out
$ echo -e 'exit\x1b[4D\x1b[Jshow myself out' | od -c
0000000   e   x   i   t 033   [   4   D 033   [   J   s   h   o   w    
0000020   m   y   s   e   l   f       o   u   t  \n

Specifically, we have

Esc [ Value D - Cursor Backward:

Moves the cursor back by the specified number of columns without changing lines. If the cursor is already in the leftmost column, ANSI.SYS ignores this sequence.

Esc [ J - Clear screen from cursor down

more info here: http://ascii-table.com/ansi-escape-sequences.php

  • What I am looking for is a tool that will process the output in this manner, and provide the result that a user would see as a simple string. Something like a terminal emulator might do the trick. – pleasemorebacon Sep 26 '14 at 16:10

Your Answer

By clicking "Post Your Answer", you acknowledge that you have read our updated terms of service, privacy policy and cookie policy, and that your continued use of the website is subject to these policies.

Not the answer you're looking for? Browse other questions tagged or ask your own question.