python中的webbrowser.open()

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/22004498/
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:04:25  来源:igfitidea点击:

webbrowser.open() in python

pythonhtml

提问by Lelouch

I have a python file html_gen.pywhich write a new htmlfile index.htmlin the same directory, and would like to open up the index.htmlwhen the writing is finished.

我有一个python文件html_gen.py,它在同一目录中写入了一个新html文件index.html,并且想index.html在写入完成后打开它。

So I wrote

所以我写了

import webbrowser
webbrowser.open("index.html");

But nothing happen after executing the .py file. If I instead put a code

但是在执行 .py 文件后什么也没有发生。如果我改为输入代码

webbrowser.open("http://www.google.com")

Safari will open google frontpage when executing the code.

Safari 会在执行代码时打开谷歌首页。

I wonder how to open the local index.html file?

我想知道如何打开本地的 index.html 文件?

采纳答案by Al Sweigart

Try specifying the "file://" at the start of the URL. Also, use the absolute path of the file:

尝试在 URL 的开头指定“file://”。另外,使用文件的绝对路径:

import webbrowser, os
webbrowser.open('file://' + os.path.realpath(filename))

回答by falsetru

Convert the filename to url using urllib.pathname2url:

使用urllib.pathname2url以下命令将文件名转换为 url :

import os
try:
    from urllib import pathname2url         # Python 2.x
except:
    from urllib.request import pathname2url # Python 3.x

url = 'file:{}'.format(pathname2url(os.path.abspath('1.html')))
webbrowser.open(url)