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

标签 python terminal python-3.4 ansi-escape

我正在写一个“libansi”。
我想捕获ansi序列\x1b[6n的返回码
我尝试了一些解决方法,但无济于事。

例子:

#!/usr/bin/python3.4
rep = os.popen("""a=$(echo "\033[6n") && echo $a""").read()

代表返回“\033[6n”...

有人有想法吗?

感谢帮助。

编辑 :
我有一个部分解决方案:
a=input(print("\033[6n", end='')

但这需要我在输入时按“输入”以获取光标位置。

最佳答案

问题是

  • 默认情况下标准输入是缓冲的,
  • 将序列写入标准输出后,终端会将其响应发送到标准输入,而不是标准输出。所以终端就像按下实际的键而不返回。

  • 诀窍是使用 tty.setcbreak(sys.stdin.fileno(), termios.TCSANOW)并在此之前通过 termios.getattr 存储终端属性在变量中恢复默认行为。与 cbreak套装,os.read(sys.stdin.fileno(), 1)您可以立即从标准输入读取。这也抑制了来自终端的 ansi 控制代码响应。
    def getpos():
    
        buf = ""
        stdin = sys.stdin.fileno()
        tattr = termios.tcgetattr(stdin)
    
        try:
            tty.setcbreak(stdin, termios.TCSANOW)
            sys.stdout.write("\x1b[6n")
            sys.stdout.flush()
    
            while True:
                buf += sys.stdin.read(1)
                if buf[-1] == "R":
                    break
    
        finally:
            termios.tcsetattr(stdin, termios.TCSANOW, tattr)
    
        # reading the actual values, but what if a keystroke appears while reading
        # from stdin? As dirty work around, getpos() returns if this fails: None
        try:
            matches = re.match(r"^\x1b\[(\d*);(\d*)R", buf)
            groups = matches.groups()
        except AttributeError:
            return None
    
        return (int(groups[0]), int(groups[1]))
    

    关于Python 3 : Capture return of `\x1b[6n` (`\033[6n` , `\e[6n` ) ansi 序列,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38465171/

    相关文章:

    python - base64.encodestring 在 python 3 中失败

    python - 如何让这个方 block 在 Tkinter 中消失

    python - 在 Linux 上运行 Tensorflow 代码时出错

    python - Robot Framework中的自定义执行状态

    linux - Bash 脚本从文本文件复制单词并在终端上运行

    java - 错误 : Could not find or load main class, 但在类路径中缺少 .jar 时有效?

    node.js - 如何像 Vim 一样以全屏模式创建 Node.js TUI 应用程序

    python - Pandas 基于列值排序

    python - 用Python计算文件中奇数和偶数的总数

    Python——这有什么问题吗?我不断收到错误消息