Home > Enterprise >  python program not running is html webpage
python program not running is html webpage

Time:12-03

this my html code

<!DOCTYPE html>
<html lang="en">
<head>

<title>pyscript demo</title>

<link rel="stylesheet" href="https://pyscript.net/latest/pyscript.css" />
<script defer src="https://pyscript.net/latest/pyscript.js"></script>
</head>

<body>
<py-script src="pythonfile.py"></py-script>

</body>
</html>

and this my python program code

lst = [["a", 45], ["b", 40], ["c", 18], ["d", 17]]

name = input("Enter your name:")

print("Searching in list")
for item in lst:
    if item[0] == name:
        print("name:", item[0], "age:", item[1])

I have tried to run python program in html webpage the html web page is working and the python code is not running is html webpage

CodePudding user response:

If you have vs-code, install "Live-Server" extension and open live-server.

or

open terminal/command-prompt in the same folder. Assuming you have named your html file as "index.html", enter following command in terminal:

python3 -m http.server 8000

then open http://0.0.0.0:8000 in your browser

CodePudding user response:

You are facing issue as mentioned below.

Access to fetch at 'pythonfile.py' from origin 'null' has been blocked by CORS policy: Cross origin requests are only supported for protocol schemes: http, data, isolated-app, chrome-extension, chrome, https, chrome-untrusted.

then you can try this instead of attaching a python file write it inline.

<py-script>
    lst = [["a", 45], ["b", 40], ["c", 18], ["d", 17]]

    name = input("Enter your name:")

    print("Searching in list")
    for item in lst:
        if item[0] == name:
            print("name:", item[0], "age:", item[1])
</py-script>

CodePudding user response:

When some thing does not work, please describe what is happening instead. In a web browser you can get more information from the developer tools Console, which can be opened by the menu or probably by pressing F12 or Ctrl Shift I (See here).

As GauravGiri already answered, the most probable reason is the difference between opening an HTML file locally and visiting it through a webserver: HTML Sites are not allowed to read the contents of other local files on your computer, while accessing them from the same webserver is allowed.

  • Related