简体   繁体   English

如何使用 python 运行特定的 Javascript 函数

[英]How to run a specific Javascript function using python

I have a Javascript file with 2 functions eg我有一个带有 2 个函数的 Javascript 文件,例如

function function1(){
console.log("Hello world")
}

function function2(){
console.log("Hello world number 2")
}

And I want to have a python function which executes either one of these function, how would I do this?我想要一个执行这些函数之一的 python 函数,我该怎么做? BTW I want to do this as I will make one of my python scripts run and generate a value and I want to use Javascript to display this value onto the HTML file fancily.顺便说一句,我想这样做,因为我将使我的一个 python 脚本运行并生成一个值,并且我想使用 Javascript 巧妙地将此值显示到 HTML 文件上。

This is possible via setting up Python's backend - then you can render frontend using proper HTML files with specified JS functionality.这可以通过设置 Python 的后端来实现 - 然后您可以使用具有指定 JS 功能的适当 HTML 文件来呈现前端。

You could use Flask in order to handle the backend in Python:您可以使用Flask来处理 Python 中的后端:

(remember to install flask before you use it pip3 install flask ) (使用之前记得先安装flask pip3 install flask

from flask import Flask, render_template
app = Flask(__name__, template_folder= "/templates")

@app.route('/function1')
def function1():
    return render_template('function1.html')

@app.route('/function2')
def function2():
    return render_template('function2.html')

app.run(port = 8000)

(The templates folder contains different websites you want to display - the ones with your JS functionalities) (模板文件夹包含您要显示的不同网站 - 具有您的 JS 功能的网站)

Now when you open your browser with localhost:8000/function1 You should see your website showing evaluated function1 value现在,当您使用localhost:8000/function1打开浏览器时,您应该会看到您的网站显示评估的function1

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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