Pergunta

Eu gostaria de saber se existe alguma maneira de determinar a cor de fundo de um terminal?

No meu caso, usando o GNOME-Terminal.
Pode ser importante, uma vez que está até o aplicativo terminal desenhar o fundo de suas janelas, o que pode até ser outra coisa que uma cor simples.

Foi útil?

Solução

Eu criei o seguinte:

#!/bin/sh
#
# Query a property from the terminal, e.g. background color.
#
# XTerm Operating System Commands
#     "ESC ] Ps;Pt ST"

oldstty=$(stty -g)

# What to query?
# 11: text background
Ps=${1:-11}

stty raw -echo min 0 time 0
# stty raw -echo min 0 time 1
printf "\033]$Ps;?\033\\"
# xterm needs the sleep (or "time 1", but that is 1/10th second).
sleep 0.00000001
read -r answer
# echo $answer | cat -A
result=${answer#*;}
stty $oldstty
# Remove escape at the end.
echo $result | sed 's/[^rgb:0-9a-f/]\+$//'

Fonte/repo/GIST: https://gist.github.com/blueyed/c8470c2aad3381c333ea3

Outras dicas

Há uma Sequência de controle Xterm por esta:

\e]11;?\a

(\e e \a são os personagens ESC e BEL, respectivamente.)

Os terminais compatíveis com Xterm devem responder com a mesma sequência, com o ponto de interrogação substituído por um x11 colorsepec, por exemplo rgb:0000/0000/0000 para preto.

Além de aparentemente rxvt somente $ colorfgbg, Não sei que mais nada existe. Principalmente as pessoas parecem ser referindo -se a Como as vim faz isso, e mesmo esse é um palpite educado, na melhor das hipóteses.

Alguns links:

Por exemplo, algum trecho relacionado de NEOVIM Edição 2764:

/*
 * Return "dark" or "light" depending on the kind of terminal.
 * This is just guessing!  Recognized are:
 * "linux"         Linux console
 * "screen.linux"   Linux console with screen
 * "cygwin"        Cygwin shell
 * "putty"         Putty program
 * We also check the COLORFGBG environment variable, which is set by
 * rxvt and derivatives. This variable contains either two or three
 * values separated by semicolons; we want the last value in either
 * case. If this value is 0-6 or 8, our background is dark.
 */
static char_u *term_bg_default(void)
{
  char_u      *p;

  if (STRCMP(T_NAME, "linux") == 0
      || STRCMP(T_NAME, "screen.linux") == 0
      || STRCMP(T_NAME, "cygwin") == 0
      || STRCMP(T_NAME, "putty") == 0
      || ((p = (char_u *)os_getenv("COLORFGBG")) != NULL
          && (p = vim_strrchr(p, ';')) != NULL
          && ((p[1] >= '0' && p[1] <= '6') || p[1] == '8')
          && p[2] == NUL))
    return (char_u *)"dark";
  return (char_u *)"light";
}

Sobre COLORFGBG Env, de Gnome Bugzilla 733423:

Dos alguns terminais que acabei de experimentar no Linux, apenas o URXVT e o Konsole o definem (os que não o fazem: Xterm, ST, Terminology, Pterm). Konsole e URXVT usam sintaxe e semântica diferentes, ou seja, para mim, Konsole define como "0; 15" (mesmo que eu use o esquema de cores "preto em amarelo claro" - então por que não "padrão" em vez de "15"?), enquanto meu URXVT o define como "0; padrão; 15" (é realmente preto em branco - mas por que três campos?). Portanto, em nenhum desses dois o valor corresponde à sua especificação.

Este é um código próprio que estou usando (através da):

def is_dark_terminal_background():
    """
    :return: Whether we have a dark Terminal background color, or None if unknown.
        We currently just check the env var COLORFGBG,
        which some terminals define like "<foreground-color>:<background-color>",
        and if <background-color> in {0,1,2,3,4,5,6,8}, then we have some dark background.
        There are many other complex heuristics we could do here, which work in some cases but not in others.
        See e.g. `here <https://stackoverflow.com/questions/2507337/terminals-background-color>`__.
        But instead of adding more heuristics, we think that explicitly setting COLORFGBG would be the best thing,
        in case it's not like you want it.
    :rtype: bool|None
    """
    if os.environ.get("COLORFGBG", None):
        parts = os.environ["COLORFGBG"].split(";")
        try:
            last_number = int(parts[-1])
            if 0 <= last_number <= 6 or last_number == 8:
                return True
            else:
                return False
        except ValueError:  # not an integer?
            pass
    return None  # unknown (and bool(None) == False, i.e. expect light by default)

Você quer dizer um método para verificar a cor do fundo do terminal ou definir a cor do terminal?

Se este último, você poderá consultar a variável de ambiente PS1 do seu terminal para obter a cor.

Há um artigo sobre o cenário (e assim derivando) as cores do terminal aqui:http://www.ibm.com/developerworks/linux/library/l-tip-prompt/

Licenciado em: CC-BY-SA com atribuição
Não afiliado a StackOverflow
scroll top