Python 调用操作系统打开url?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/4216985/
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
Call to operating system to open url?
提问by Bolster
What can I use to call the OS to open a URL in whatever browser the user has as default? Not worried about cross-OS compatibility; if it works in linux thats enough for me!
我可以使用什么来调用操作系统在用户默认使用的任何浏览器中打开 URL?不担心跨操作系统兼容性;如果它在 linux 中工作,那对我来说就足够了!
采纳答案by kobrien
Here is how to open the user's default browser with a given url:
以下是如何使用给定的 url 打开用户的默认浏览器:
import webbrowser
webbrowser.open(url[, new=0[, autoraise=True]])
Here is the documentation about this functionality. It's part of Python's stdlibs:
这是有关此功能的文档。它是 Python 标准库的一部分:
http://docs.python.org/library/webbrowser.html
http://docs.python.org/library/webbrowser.html
I have tested this successfully on Linux, Ubuntu 10.10.
我已经在 Linux Ubuntu 10.10 上成功测试了这个。
回答by Aaron Digulla
Have a look at the webbrowser module.
回答by Ivo Wetzel
回答by bobince
Personally I really wouldn'tuse the webbrowsermodule.
我个人真的不会使用该webbrowser模块。
It's a complicated mess of sniffing for particular browsers, which will won't find the user's default browser if they have more than one installed, and won't find a browser if it doesn't know the name of it (eg Chrome).
对于特定浏览器,这是一团复杂的嗅探,如果用户安装了多个浏览器,它将无法找到用户的默认浏览器,如果不知道浏览器的名称(例如 Chrome),则无法找到浏览器。
Better on Windows is simply to use the os.startfilefunction, which also works on a URL. On OS X, you can use the opensystem command. On Linux there's xdg-open, a freedesktop.org standard command supported by GNOME, KDE and XFCE.
在 Windows 上更好的是使用该os.startfile功能,该功能也适用于 URL。在 OS X 上,您可以使用opensystem 命令。在 Linux 上xdg-open,有 GNOME、KDE 和 XFCE 支持的 freedesktop.org 标准命令。
if sys.platform=='win32':
os.startfile(url)
elif sys.platform=='darwin':
subprocess.Popen(['open', url])
else:
try:
subprocess.Popen(['xdg-open', url])
except OSError:
print 'Please open a browser on: '+url
This will give a better user experience on mainstream platforms. You could fall back to webbrowseron other platforms, perhaps. Though most likely if you're on an obscure/unusual/embedded OS where none of the above work, chances are webbrowserwill fail too.
这将在主流平台上提供更好的用户体验。webbrowser也许你可以回到其他平台。尽管最有可能的是,如果您使用的是一个晦涩的/不寻常的/嵌入式操作系统,而上述操作都不起作用,但也有可能webbrowser会失败。
回答by Kenial
Then how about mixing codes of @kobrien and @bobince up:
那么如何混合@kobrien 和@bobince 的代码:
import subprocess
import webbrowser
import sys
url = 'http://test.com'
if sys.platform == 'darwin': # in case of OS X
subprocess.Popen(['open', url])
else:
webbrowser.open_new_tab(url)

