xterm兼容的TTY颜色查询命令?
问题描述:
下面是从https://github.com/rocky/bash-term-background中提取的一些shell代码来获取终端背景颜色。我想模仿在Python这种行为,以便它可以检索值过:xterm兼容的TTY颜色查询命令?
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 '\033]10;?\07\033]11;?\07'", shell=True)
将在Python 2.7一个合理的翻译,但我没有得到任何输出。在bterm运行在一个Xterm兼容的终端给出:
rgb:e5e5e5/e5e5e6
rgb:000000/000000
但是在python中,我什么也没有看到。
更新:正如Mark Setchell所建议的,也许部分问题是在子流程中运行。所以,当我将python代码更改为:
print(check_output(["echo", "-ne" "'\033]10;?\07\033]11;?07'"]))
我现在看到RGB值输出,但只有在程序终止后。所以这表明这个问题是挂钩看到我猜测xterm异步发送的输出。
月2日更新:基于meuh的代码我放在这个更全面的版本https://github.com/rocky/python-term-background
答
您需要只写转义序列到stdout并将其设置为原始模式后读取标准输入的响应:
#!/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('\033]10;?\07\033]11;?\07')
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")
然后你在下一行开始另一个完全独立的子进程来读取输出吗? –
'shell = True'暗示是。当我删除该参数时,我现在可以看到xterm的输出。但没有捕获到变量中。因此,我可能需要做的就是事先重定向stdout并等待,或者直接从终端读取连接。我已经修改了这个问题以包含这个新的重要信息。 – rocky