Print a hyperlink in the terminal
03:31 29 Jan 2022

I can use this special escape sequence to print a hyperlink in bash:

echo -e '\e]8;;http://example.com\e\\This is a link\e]8;;\e\\\n'

Result (Link I can click on):

This is a link

Now I want to generate this in Python:

print('\e]8;;http://example.com\e\\This is a link\e]8;;\e\\\n')
\e]8;;http://example.com\e\This is a link\e]8;;\e\

print(r'\e]8;;http://example.com\e\\This is a link\e]8;;\e\\\n')
\e]8;;http://example.com\e\\This is a link\e]8;;\e\\\n

As you can see, the escape sequence is not interpreted by the shell. Other escape sequences, like the one for bold text, work:

print('\033[1mYOUR_STRING\033[0m')
YOUR_STRING    # <- is actually bold

How can I get Python to format the URL correctly?

python terminal hyperlink