如何在 Python 中插入链接

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/22125114/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-19 00:17:29  来源:igfitidea点击:

How to insert links in Python

pythonhtml

提问by Code Newbie

Is it possible to add Links into Python script and print it out? Like in HTML,once it was clicked,we will be redirected to the URL.

是否可以将链接添加到 Python 脚本中并打印出来?就像在 HTML 中一样,一旦被点击,我们将被重定向到 URL。

<a href="URL">Click Here To Login</a> 

回答by icedtrees

It all depends on where you want to print it out to. Some output locations do not support clickable hyperlinks.

这一切都取决于您要将其打印到何处。某些输出位置不支持可点击的超链接。

For example, if you printed your output to a basic terminal, you would not be able to click on it.

例如,如果您将输出打印到基本终端,您将无法单击它。

One suggestion is to use python's webbrowsermodule to open links:

一种建议是使用 python 的webbrowser模块打开链接:

import webbrowser
webbrowser.open("http://www.example.com")

, which will open the link for you in a new window.

,这将在新窗口中为您打开链接。

You could also output the text to a HTML file and open the HTML file in a web browser for the link:

您还可以将文本输出到 HTML 文件并在 Web 浏览器中打开 HTML 文件以获取链接:

open("link.html", "w").write('<a href="http://www.example.com"> Link </a>')

回答by Red Cricket

Yes it is possible here is a simple python cgi script that does what you describe.

是的,这里有一个简单的 python cgi 脚本,它可以执行您所描述的操作。

print "Content-type: text/html"
print

print """
<html>
<head><title>Sample</title></head>
<body>
<a href='http://google.com'>google</a>
</body></html>
"""

you can learn more about cgi here http://en.wikipedia.org/wiki/Common_Gateway_Interface

你可以在这里了解更多关于 cgi 的信息http://en.wikipedia.org/wiki/Common_Gateway_Interface

回答by egmont

Recently (in 2017) a few terminal emulators (namely iTerm2, GNOME Terminal, and Tilix; hopefully more to follow) have added support for custom hyperlinks.

最近(2017 年)一些终端模拟器(即 iTerm2、GNOME 终端和 Tilix;希望有更多后续)增加了对自定义超链接的支持。

Assuming your python app's output goes to such a terminal emulator, you can create ctrl+clickable (cmd+clickable on mac) hyperlinks like this:

假设您的 python 应用程序的输出到这样的终端模拟器,您可以创建 ctrl+clickable(在 mac 上为 cmd+clickable)超链接,如下所示:

print("\x1b]8;;http://example.com/\aCtrl+Click here\x1b]8;;\a")

Further technical details are here.

进一步的技术细节在这里