1

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?

1 Answer 1

1

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
0000033

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

1
  • 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.
    – yobiscus
    Sep 26, 2014 at 16:10

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

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