2017-07-31 36 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