2017-07-31 39 views
0

下面是从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

+1

然后你在下一行开始另一个完全独立的子进程来读取输出吗? –

+0

'shell = True'暗示是。当我删除该参数时,我现在可以看到xterm的输出。但没有捕获到变量中。因此,我可能需要做的就是事先重定向stdout并等待,或者直接从终端读取连接。我已经修改了这个问题以包含这个新的重要信息。 – rocky

回答

1

您需要只写转义序列到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") 
+0

谢谢。这很接近。在编辑中有两个很容易修复的问题。而且我不确定我是否知道如何修复。首先,我们应该检查stdin是否是tty。其次,读取应该有一个超时。最后一个问题是,在一个非xterm兼容的终端上,你会看到转义字符串被回显,我不希望这样。 – rocky

+0

嗯。也许我需要像POSIX shell'stty -echo'命令? – rocky

+0

我觉得'setr​​aw()'已经清除回声位。您可以查找“TERM”值,只接受像'xterm'这样的知识。 – meuh