简体   繁体   中英

How can I run a Python script when an HTML page is loaded?

I want to make a variable with Python, and then console.log() the variable in JavaScript. I know how to access the variable in JavaScript, but I don't know how to make the Python script run when the page is loaded. How can I do this?

Unlike Javascript, you can't run Python directly in the browser. You would need Python to run server-side. A possible alternative may be to use transcrypt to generate javascript equivalents of Python for a frontend-only solution.

For instance, transcrypt allows you to "import" python modules into JavaScript. Here, a python script called hello.py is "imported" into the context and can be called form javascript like hello.solarSystem.greet()

    <script type="module">import * as hello from './__target__/hello.js'; window.hello = hello;</script>
    <h2>Hello demo</h2>
    
    <p>
    <div id = "greet">...</div>
    <button onclick="hello.solarSystem.greet ()">Click me repeatedly!</button>
    
    <p>
    <div id = "explain">...</div>
    <button onclick="hello.solarSystem.explain ()">And click me repeatedly too!</button>

See the transcrypt docs for more info.

Otherwise, you'd probably be running a Python webserver on the backend for this use-case. Something like flask .

from flask import Flask, render_template_string

app = Flask(__name__)

def do_something():
    """Returns an interesting value"""
    return "foo"

template = """
<html>
<script>
console.log('{{ value }}')
</script>
"""

@app.route('/')
def home():
    my_value = do_something()
    return render_template_string(template, value=my_value)

app.run(debug=True)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM