Print a hyperlink in the terminal
Asked Answered
S

2

6

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?

Subedit answered 29/1, 2022 at 9:51 Comment(0)
F
3

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' ) )
Feingold answered 29/1, 2022 at 10:31 Comment(0)
P
1

See Hyperlinks in terminal emulators for a reference document.

def hyperlink(url: str, text: str = None, parameters: dict = None) -> str:
    if text is None:
        text = url
    if parameters is None:
        parameters = {}
    kvs = ":".join("{}={}".format(k, v) for k, v in parameters.items())
    template = "\x1b]8;{};{}\x1b\\{}\x1b]8;;\x1b\\"
    result = template.format(parameters, url, text)
    return result

Demo:

>>> url = "https://gist.github.com/egmontkob/eb114294efbcd5adb1944c9f3cb5feda"
>>> text = "cmd+click here"
>>> hyperlink(url, text)
'\x1b]8;{};https://gist.github.com/egmontkob/eb114294efbcd5adb1944c9f3cb5feda\x1b\\cmd+click here\x1b]8;;\x1b\\'
>>> print(hyperlink(url, text))
cmd+click here

You can also use Rich to render terminal hyperlinks.

pip install 'rich >= 1.1'

This autodetects if the terminal emulator supports links, and allows using a simple markdown-like syntax:

from rich import print
print("[link=https://example.org]click me![/link]")
Peabody answered 28/7, 2024 at 21:25 Comment(0)

© 2022 - 2025 — McMap. All rights reserved.