简体   繁体   中英

Writing string with ANSI escape sequences to file

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.

Is there a way to achieve a 'clean' write to file, either using some python module, or some bash utility? Surely there must be some module out there that can do this for me?

less is interpreting the control characters.

You can get around this with the -r command line option:

$ less -r file.txt 
show myself out

From the manual:

   -r or --raw-control-chars
          Causes "raw" control characters to be displayed.  The default is
          to display control characters  using  the  caret  notation;  for
          example, a control-A (octal 001) is displayed as "^A".  Warning:
          when the -r option is used, less cannot keep track of the actual
          appearance  of  the screen (since this depends on how the screen
          responds to each type of control character).  Thus, various dis‐
          play  problems may result, such as long lines being split in the
          wrong place.

The raw control characters are sent to the terminal, which then interprets them as cat would.

As others have stated, you would need to interpret the characters yourself before writing them to a file.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM