在Python中设置GNOME终端窗口标题?

时间:2014-09-16 15:10:39

标签: python terminal

如何从Python设置GNOME终端的窗口标题?

我正在从不同的终端运行几个python脚本。我希望python脚本一旦执行,就会自动将窗口标题设置为一些我可以在脚本中修改的状态文本。

3 个答案:

答案 0 :(得分:3)

您可以使用XTerm control sequence

print(b'\33]0;title you want\a')

注意:上述声明将打印其他换行符。为避免这种情况,请使用sys.stdout.write

import sys
sys.stdout.write(b'\33]0;title you want\a')
sys.stdout.flush()

在Python 3.x中:

print('\33]0;title you want\a', end='')
sys.stdout.flush()

在Python 3.3 +中:

print('\33]0;title you want\a', end='', flush=True)

OR

sys.stdout.buffer.write(b'\33]0;title you want\a')
sys.stdout.buffer.flush()

答案 1 :(得分:1)

Python3接受的答案是错误的。这适用于Python> = 3.6:

terminal_title = "title you want"
print(f'\33]0;{terminal_title}\a', end='', flush=True)

flush至关重要;看评论。

我也不建议像另一个答案一样检查if os.environ['TERM'] == 'xterm',因为有些终端即使支持OSC转义码也未通过检查:

[navin@Radiant ~]$ echo $TERM
xterm-256color
[navin@Radiant ~]$ echo $TERM_PROGRAM
iTerm.app

答案 2 :(得分:0)

添加到falsetru's answer,Python(2和3)也支持将常规字符串写入stdout:

import sys
sys.stdout.write('\33]0;title you want\a')
sys.stdout.flush()

顺便说一句,我把它放在我的~/.pythonstartup文件中,以便在打开Python shell时设置标题:

import os
import sys

def set_xterm_title(title='Python %d.%d.%d' % sys.version_info[:3]):
    '''
    Set XTerm title using escape sequences.
    By default, sets as 'Python' and the version number.
    '''
    sys.stdout.write('\33]0;' + title + '\a')
    sys.stdout.flush()

# Make sure this terminal supports the OSC code (\33]),
# though not necessarily that it supports setting the title.
# If this check causes compatibility issues, you can add
# items to the tuple, or remove the check entirely.
if os.environ.get('TERM') in (
        'xterm',
        'xterm-color',
        'xterm-256color',
        'linux',
        'screen',
        'screen-256color',
        'screen-bce',
        ):
    set_xterm_title()