python - 将带有 ANSI 转义序列的字符串写入文件

标签 python bash ansi-escape

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

例如,给定字符串 exit\x1b[4D\x1b[Jshow myself 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 myself out),而实际上我希望它“干净”地存储,因为它在使用打印功能时显示(show myself out) )。

打印结果或“cat”文件准确地显示了我想要显示的内容,但我猜测终端正在转换输出。

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

最佳答案

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

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

关于python - 将带有 ANSI 转义序列的字符串写入文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26005946/

相关文章:

python - 为什么这个 asyncio.Task 永远不会完成取消?

python - Keras 值错误 : input 0 is incompatible with layer flatten_11

macos - 可以让 Terminal.app 尊重 ANSI 转义码吗?

Python 3 : Capture return of `\x1b[6n` (`\033[6n` , `\e[6n` ) ansi 序列

python - 获取file1的相对路径(相对于file2的路径,file1在file2的子文件夹中)

构建查询字符串时出现 Python TypeError

macos - 从 Bash shell 脚本发送邮件

linux - 在 linux 中的嵌套 for 循环中调用可执行文件

mysql - Shell 脚本 - 下载文件 - Mysql 替换

java - BASH 控制序列解析器或正则表达式?