1

我正在使用的一个 python 模块提供了一个钩子,允许在将用户键盘输入发送到 shell 终端之前捕获它。我面临的问题是它逐个字符地捕获输入,这使得当用户执行退格或移动光标等操作时难以捕获输入命令。

例如,给定字符串exit\x1b[4D\x1b[Jshow 我自己 out,将发生以下情况:

>>> 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

less 命令显示原始命令(exit\x1b[4D\x1b[Jshow 我自己出来),而实际上我希望它“干净”地存储,因为它在使用打印功能时显示(展示自己)。

打印结果,或者'cat'ing文件显示了我想要显示的内容,但我在这里猜测终端正在转换输出。

有没有办法使用一些 python 模块或一些 bash 实用程序来实现对文件的“干净”写入?肯定有一些模块可以为我做到这一点吗?

4

1 回答 1

2

less正在解释控制字符。

您可以使用-r命令行选项解决此问题:

$ less -r file.txt 
show myself out

从手册:

   -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.

原始控制字符被发送到终端,然后终端按原样解释它们cat

正如其他人所说,在将字符写入文件之前,您需要自己解释字符。

于 2014-09-24T11:06:27.953 回答