pythonterminalhyperlink

Print a hyperlink in the terminal


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?


Solution

  • 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' ) )