Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Set GNOME terminal window title in Python?

How can I set the window title of a GNOME terminal from Python?

I am running several python scripts from different terminals. I would like that the python script, once executed, automatically set the window title to some status text that I can modify from within the script.

like image 568
becko Avatar asked Jun 12 '26 07:06

becko


2 Answers

You can use XTerm control sequence:

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

NOTE: Above statement will print additional newline. To avoid it, use sys.stdout.write:

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

In Python 3.x:

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

In 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()
like image 52
falsetru Avatar answered Jun 13 '26 22:06

falsetru


The accepted answer was wrong for Python3. This works on Python >= 3.6:

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

The flush is essential; See comments.

I also do not recommend checking if os.environ['TERM'] == 'xterm' like another answer does because some terminals fail that check even though they support the OSC escape code:

[navin@Radiant ~]$ echo $TERM
xterm-256color
[navin@Radiant ~]$ echo $TERM_PROGRAM
iTerm.app
like image 29
Navin Avatar answered Jun 14 '26 00:06

Navin