Setting Titles

./title.py 'badger badger 🍄'

While playing around with terminal escape sequences, I realised that it is possible to set the window title in both xterm like terminals (Mac OS X’s terminal falls into that category) and screen like terminal emulators (tmux, I’m currently switching to, falls into that category). Sadly the escape sequences are different (nothing is simple), and don’t seem standard enough to be part of Python curses library.

So I wrote a very simple command that sets the title according to the current terminal.

#!/usr/bin/python
# -*- coding: utf-8 -*-

import sys
import os

def xterm_title(title):
  if not sys.stdout.isatty():
    return
  sys.stdout.write('\x1b]0;' +  title + '\a')

def screen_title(title):
  if not sys.stdout.isatty():
    return
  sys.stdout.write('\x1bk' + title + '\x1b\\')

def main(argv):
  term = os.getenv('TERM')
  text = ' '.join(argv)
  if ('xterm' in term):
    xterm_title(text)
  elif ('screen' in term):
    screen_title(text)


if __name__ == "__main__":
    main(sys.argv[1:])

If you wonder why I’m using \x1b to represent the escape character, the answer is simple: Python does not define \e.

Leave a Reply