Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to run html code in python with web output using vscode

I know you guys will remove this question, cause this has been asked, but i can really not understand this question!! Stack overflow has been useless for me due to you guys rejecting my questions even though the answers were hard to understand! Please listen!

The problem:
I have tried to run this code in vscode and was hoping that it would open the web output for the myfile.html:

runner.py

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

import webbrowser
webbrowser.open_new_tab('myfile.html')

myfile.html

<!DOCTYPE html>
<html lang="en">
    <head>
        <meta charset="utf-8" name="viewport" content="inital-scale=1 , width=device-width">
        <title> a file waiting to be opened with python! </title>
    </head>
    <body>
        <header>
            <h1> The top! </h1>
            
            
        </header>
        <main>
            <img src="file.jpg">
            <p> a paragraph</p>
        </main>
        
    </body>
</html>

and i also have file.jpg in the same folder. But vscode just does nothing ! I have seen on stack overflow and for the other people it has seemed to be working but for me it is not!
Please answer this question, or else i would never use stack overflow again! Also, if there is something wrong with my question or anything else, please tell me and do not close my question!

This was the console output:
cd /Users/aarav/html\ in\ python ; /usr/bin/env /usr/local/bin/python3 /Users/aarav/.vscode/extensions/ms-python.pyt
hon-2023.13.11951037/pythonFiles/lib/python/debugpy/adapter/../../debugpy/launcher 56528 — /Users/aarav/html\ in\ python/runner.py but it did not open a new tab!

Also PLEASE DO NOT CLOSE THIS QUESTION!!!!

>Solution :

webbrowser.open_new_tab requires a URL, not a file path.

To specify local files in a URL use the file://absolute/path/to/file/ scheme:

import webbrowser
import os

webbrowser.open_new_tab(f"file://{os.path.abspath('myfile.html')}")

This code uses the os module to get the absolute path of the file, and then convert it to a URL. You could use a server to serve the file and then use the servers url.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading