【问题标题】:webbrowser.open() in pythonpython中的webbrowser.open()
【发布时间】:2014-03-27 02:29:08
【问题描述】:

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

所以我写了

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

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

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

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

不知如何打开本地的index.html文件?

【问题讨论】:

  • 看到这个答案:stackoverflow.com/a/5943706/771848
  • 如果调用内置的open('index.html') 会报错吗?它检查您是否可以打开文件进行阅读。
  • 无法在 Python 2.7.6、Ubuntu 14.04、Firefox 47 上重现。
  • webbrowser.open('index.html', new=2, autoraise=True) 工作正常,分号是否打破它?

标签: python html


【解决方案1】:

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

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

【讨论】:

  • 注意:需要导入 Python os 模块才能工作:import os
【解决方案2】:

使用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)

【讨论】:

    猜你喜欢
    • 2011-02-07
    • 1970-01-01
    • 1970-01-01
    • 2014-04-22
    • 2020-05-12
    • 2017-10-23
    • 2015-03-04
    • 2018-06-13
    • 1970-01-01
    相关资源
    最近更新 更多