5

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 3.10:

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?

F. Hauri
  • 58,205
  • 15
  • 105
  • 122
Richard Neumann
  • 2,630
  • 1
  • 21
  • 43
  • Does this answer your question? [How to print colored text to the terminal](https://stackoverflow.com/questions/287871/how-to-print-colored-text-to-the-terminal) – F. Hauri Jan 29 '22 at 10:05
  • 2
    From [This answer](https://stackoverflow.com/a/21786287/1765658), with some tries: `print('\x1b]8;;' + 'http://example.com' + '\x1b\\' + 'This is a link' + '\x1b]8;;\x1b\\\n' )` – F. Hauri Jan 29 '22 at 10:12
  • Answer published! – F. Hauri Jan 29 '22 at 10:31

1 Answers1

2

From This answer, after some tries:

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

Then better:

print( '\x1b]8;;%s\x1b\\%s\x1b]8;;\x1b\\' %
       ( 'http://example.com' , 'This is a link' ) )
F. Hauri
  • 58,205
  • 15
  • 105
  • 122