xterm 兼容的 TTY 颜色查询命令?

An xterm-compatible TTY color query command?

这是从 https://github.com/rocky/bash-term-background 中提取的一些 shell 代码,用于获取终端背景颜色。我想在 Python 中模仿这种行为,这样它也可以检索值:

stty -echo
# Issue command to get both foreground and
# background color
#            fg       bg
echo -ne '\e]10;?\a\e]11;?\a'
IFS=: read -t 0.1 -d $'\a' x fg
IFS=: read -t 0.1 -d $'\a' x bg
stty echo
# RGB values are in $fg and $bg

我可以翻译大部分内容,但我遇到问题的部分是 echo -ne '\e]10;?\a\e]11;?\a'

我认为:

output = subprocess.check_output("echo -ne '3]10;?3]11;?'", shell=True)

在 Python 2.7 中是一个合理的翻译,但我没有得到任何输出。在与 Xterm 兼容的终端中 bash 中的 运行 给出:

rgb:e5e5e5/e5e5e6
rgb:000000/000000

但在 python 中我什么也没看到。

Update:正如 Mark Setchell 所说,部分问题可能出在子进程中 运行。因此,当我将 python 代码更改为:

 print(check_output(["echo", "-ne" "'3]10;?3]11;?07'"]))

我现在可以看到 RGB 值输出,但只能在程序终止后才能看到。所以这表明问题在于连接以查看我猜 xterm 正在异步发送的输出。

第二次更新:基于meuh的代码,我在https://github.com/rocky/python-term-background

中放置了更完整的版本

您只需将转义序列写入标准输出并在将其设置为原始模式后读取标准输入上的响应:

#!/usr/bin/python3
import os, select, sys, time, termios, tty

fp = sys.stdin
fd = fp.fileno()

if os.isatty(fd):
    old_settings = termios.tcgetattr(fd)
    tty.setraw(fd)
    print('3]10;?3]11;?')
    time.sleep(0.01)
    r, w, e = select.select([ fp ], [], [], 0)
    if fp in r:
        data = fp.read(48)
    else:
        data = None
        print("no input available")
    termios.tcsetattr(fd, termios.TCSADRAIN, old_settings)
    if data:
        print("got "+repr(data)+"\n")
else:
    print("Not a tty")