Changing the terminal title bar with Python

Steven D'Aprano steve+comp.lang.python at pearwood.info
Fri Oct 18 12:46:19 EDT 2013


You might find this useful, or just for fun, but on POSIX systems (Linux, 
Unix, Apple Mac, but not Windows) you can change the title of the 
terminal window from Python. Not all terminals support this feature, but 
those which emulate an xterm do.

import os

GOOD_TERMINALS = ["xterm"]

def set_title(msg):
    # Tell the terminal to change the current title.
    if os.getenv("TERM") in GOOD_TERMINALS:
        print("\x1B]0;%s\x07" % msg)
    

If this doesn't work for you, check that your terminal actually is an 
xterm, or at least emulates one correctly. Some other terminal types may 
also work, in which case you'll need to add them into the GOOD_TERMINALS 
list. 

If your terminal is configured wrongly, changing the title may fail, for 
example if the locale is not set correctly. In this case, I can't help 
you, but googling may lead to some solutions.

Another thing which may interfere with this is the Unix "screen" program. 
If so, try adding a line like this to your .screenrc file:

termcapinfo xterm 'hs:ts=\E]2;:fs=\007:ds=\E]2;screen\007'

See here for more information: 
http://www.tldp.org/HOWTO/Bash-Prompt-HOWTO/x395.html

Some terminals, like Konsole, may insist on appending their own text 
after the title.


How about reading the terminal title?

xterms used to have a feature where they would write the title back to 
standard input. Unfortunately, it has been disabled for security reasons, 
so I haven't been able to get this to work (not that I tried very 
hard...), but you might like to experiment with this:

import sys
def get_title():
    # Read the current terminal title.
    # This is usually disabled for security reasons.
    if os.getenv("TERM") in GOOD_TERMINALS:
        print("\x1B[23t")
        return sys.stdin.read()
    return ''


More recent xterms allegedly implement a title stack, where you can tell 
the terminal to save the current title, then restore it afterwards. 
Again, I haven't been able to get this to work, but have fun 
experimenting with it:

def save_title():
    # Tell the terminal to save the current title.
    if os.getenv("TERM") in GOOD_TERMINALS:
        print("\x1B[22t")

def restore_title():
    # Restore the previously saved terminal title.
    if os.getenv("TERM") in GOOD_TERMINALS:
        print("\x1B[23t")


This post was inspired by this recipe on ActiveState:

http://code.activestate.com/recipes/578662



-- 
Steven



More information about the Python-list mailing list