我可以使用这个特殊的转义序列在 bash 中打印超链接:
echo -e '\e]8;;http://example.com\e\\This is a link\e]8;;\e\\\n'
结果(我可以单击的链接):
This is a link
现在我想在 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
如您所见,转义序列是不被 shell 解释。 其他转义序列(例如粗体文本的转义序列)也可以工作:
print('\033[1mYOUR_STRING\033[0m')
YOUR_STRING # <- is actually bold
如何让 Python 正确格式化 URL?
Python 没有解释这些转义序列,因为它们是特定于终端的。在这种情况下,
\e
序列被解释为 xterm-compatible 终端中的转义字符,用于启动控制序列。
要在 Python 中实现类似的效果,你可以使用专为此类功能设计的库。一个流行的选择是
rich
库,它提供了丰富的终端内容格式化功能,包括超链接。
以下是使用
rich
库创建可点击超链接的示例:
from rich.console import Console
from rich.text import Text
console = Console()
text = Text("This is a ")
link = "http://example.com"
text.append(f"link", style=f"link {link}")
console.print(text)
这会在终端中打印“This is a link”,其中“link”一词是可点击的,指向 http://example.com。
rich
库提供了许多其他格式化选项,包括粗体、颜色、表格等。你可以查看其文档以获取更多信息:https://rich.readthedocs.io/
另外,如果你只想打印原始转义序列,而不需要 Python 解释它们,你可以使用
print(r"...")
语法,其中
r
表示“原始字符串”。这样可以防止 Python 解释字符串中的任何转义字符。例如:
print(r'\e]8;;http://example.com\e\\This is a link\e]8;;\e\\\n')
这将打印字符串,包括
\e
序列,而不进行任何解释。但是,这只有在你确定终端能够正确解释这些序列的情况下才有效。