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.
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()
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With