【问题标题】:Is there a way that I can preview my html file?有没有办法可以预览我的 html 文件?
【发布时间】:2018-11-23 19:57:26
【问题描述】:

有没有办法可以使用 python 预览我的 html 文件?我的 html 文件基本上是一个条形图,我希望用户在他或她运行 python 文件时看到它。

【问题讨论】:

    标签: javascript python html


    【解决方案1】:

    您可以使用FlaskDjango 纯python 中的python 网络框架。我目前正在使用 Django,它甚至带有开发人员服务器和模板标签,这让生活变得超级简单。

    姜戈tutorial

    【讨论】:

    • 我该怎么做?我尝试使用像 Flask 这样的 Web 框架,但我一直得到一个空白页面。这是我写的关于 Flask 的帖子。 stackoverflow.com/questions/53439936/…
    • 我对flask不太熟悉,但我可以在django中指导你
    • 好的,我会尽我所能。
    • 我建议你在虚拟环境中安装 django 但你也可以直接安装到你的系统中
    【解决方案2】:

    用户可以运行python命令生成本地html文件,然后用本地浏览器打开

    import webbrowser, os
    
    # first you save html content to a file
    filename = 'yourpage.html'
    html_content = "<html><head>This is header</head><body>This is body</body></html>"
    f = open(filename,"w")
    f.write(html_content)
    f.close()
    
    # then you use it with local browser
    webbrowser.open('file://' + os.path.realpath(filename))
    

    使用 python 3.6 和 2.7 在 Ubuntu 上测试

    【讨论】:

    • 如果它是bar charmathplotlib 也可以在没有 HTML 的情况下完成这项工作
    • 我不确定这是否对他有用,因为他可以自己在浏览器中打开 html 而不需要 python。我认为他以后想做一些更复杂的事情。
    【解决方案3】:

    这与@Theo 的answer 类似,不同之处在于它使用命名的临时文件并将[默认] 浏览器作为单独的进程生成。

    import subprocess
    import sys
    from tempfile import NamedTemporaryFile
    
    html = '''
        <!DOCTYPE html>
        <html>
          <head>
            <title>Chart Preview</title>
          </head>
          <body>
            <p>Here's your bar chart:</p>
              <!-- html for your bar chart goes here -->
          </body>
        </html>
    '''
    
    with NamedTemporaryFile(mode='wt', suffix='.html', delete=False) as temp_file:
        temp_file.write(html)
        temp_filename = temp_file.name  # Save temp file's name.
    
    command = '"%s" -m webbrowser -n "file://%s"' % (sys.executable, temp_filename)
    browser = subprocess.Popen(command, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
    
    print('back in the main script...')
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2016-01-10
      • 1970-01-01
      • 1970-01-01
      • 2012-11-24
      • 1970-01-01
      • 2022-10-23
      • 2023-01-12
      • 2021-10-23
      相关资源
      最近更新 更多