简体   繁体   English

如何在 HTML 中运行 Python 脚本?

[英]How can I run a Python script in HTML?

Currently I have some Python files which connect to an SQLite database for user inputs and then perform some calculations which set the output of the program.目前我有一些 Python 文件连接到SQLite数据库供用户输入,然后执行一些设置程序 output 的计算。 I'm new to Python web programming and I want to know: What is the best method to use Python on the web?我是 Python web 编程的新手,我想知道:在 web 上使用 Python 的最佳方法是什么?

Example: I want to run my Python files when the user clicks a button on the web page.示例:我想在用户单击 web 页面上的按钮时运行我的 Python 文件。 Is it possible?可能吗?

I started with Django .我从Django开始。 But it needs some time for the learning.但它需要一些时间来学习。 And I also saw something called CGI scripts.我还看到了一种叫做CGI脚本的东西。 Which option should I use?我应该使用哪个选项?

You are able to run a Python file using HTML using PHP .您可以使用PHP使用 HTML 运行 Python 文件。

Add a PHP file as index.php :添加一个 PHP 文件作为index.php

<html>
<head>
<title>Run my Python files</title>
<?PHP
echo shell_exec("python test.py 'parameter1'");
?>
</head>

Passing the parameter to Python将参数传递给 Python

Create a Python file as test.py :创建一个 Python 文件作为test.py

import sys
input=sys.argv[1]
print(input)

Print the parameter passed by PHP.打印 PHP 传递的参数。

It probably would depend on what you want to do.这可能取决于你想做什么。 I personally use CGI and it might be simpler if your inputs from the web page are simple, and it takes less time to learn.我个人使用 CGI,如果你从网页输入的内容很简单,它可能会更简单,而且学习时间更少。 Here are some resources for it:这里有一些资源:

However, you may still have to do some configuring to allow it to run the program instead of displaying it.但是,您可能仍需要进行一些配置以允许它运行程序而不是显示它。

Here's a tutorial on that: Apache Tutorial: Dynamic Content with CGI这是一个教程: Apache 教程:使用 CGI 的动态内容

If your web server is Apache you can use the mod_python module in order to run your Python CGI scripts.如果您的 Web 服务器是Apache ,您可以使用mod_python模块来运行您的 Python CGI 脚本。

For nginx , you can use mod_wsgi .对于nginx ,您可以使用mod_wsgi

Thanks to WebAssembly and the Pyodide project, it is now possible to run Python in the browser.感谢WebAssemblyPyodide项目,现在可以在浏览器中运行 Python。 Check out my tutorial on it.看看我的教程

 const output = document.getElementById("output") const code = document.getElementById("code") function addToOutput(s) { output.value += `>>>${code.value}\n${s}\n` output.scrollTop = output.scrollHeight code.value = '' } output.value = 'Initializing...\n' // Init pyodide languagePluginLoader.then(() => { output.value += 'Ready!\n' }) function evaluatePython() { pyodide.runPythonAsync(code.value) .then(output => addToOutput(output)) .catch((err) => { addToOutput(err) }) }
 <!DOCTYPE html> <head> <script type="text/javascript"> // Default Pyodide files URL ('packages.json', 'pyodide.asm.data', etc.) window.languagePluginUrl = 'https://pyodide-cdn2.iodide.io/v0.15.0/full/'; </script> <script src="https://pyodide-cdn2.iodide.io/v0.15.0/full/pyodide.js"></script> </head> <body> Output: </div> <textarea id='output' style='width: 100%;' rows='10' disabled></textarea> <textarea id='code' rows='3'> import numpy as np np.ones((10,)) </textarea> <button id='run' onclick='evaluatePython()'>Run</button> <p>You can execute any Python code. Just enter something in the box above and click the button. <strong>It can take some time</strong>.</p> </body> </html>

There's a new tool, PyScript , which might be helpful for that.有一个新工具PyScript可能对此有所帮助。

Official website官方网站

GitHub repository GitHub存储库

You can't run Python code directly你不能直接运行 Python 代码

You may use Python Inside HTML .您可以使用Python Inside HTML

Or for inside PHP this:或者对于PHP内部这个:

http://www.skulpt.org/

You should try the Flask or Django frameworks.您应该尝试FlaskDjango框架。 They are used to integrate Python and HTML.它们用于集成 Python 和 HTML。

There is a way to do it with Flask !有一种方法可以用Flask做到这一点!

Installation安装

First you have to type pip install flask .首先你必须输入pip install flask

Setup设置

You said when a user clicks on a link you want it to execute a Python script您说过,当用户单击链接时,您希望它执行 Python 脚本

from flask import *
# Importing all the methods, classes, functions from Flask

app = Flask(__name__)

# This is the first page that comes when you
# type localhost:5000... it will have a tag
# that redirects to a page
@app.route("/")
def  HomePage():
    return "<a href='/runscript'>EXECUTE SCRIPT </a>"

# Once it redirects here (to localhost:5000/runscript),
# it will run the code before the return statement
@app.route("/runscript")
def ScriptPage():
    # Type what you want to do when the user clicks on the link.
    #
    # Once it is done with doing that code... it will
    # redirect back to the homepage
    return redirect(url_for("HomePage"))

# Running it only if we are running it directly
# from the file... not by importing
if __name__ == "__main__":
    app.run(debug=True)

You should use Py Code because it could run Any python script In html Like this:您应该使用 Py 代码,因为它可以运行 html 中的任何 python 脚本,如下所示:

 <py-script>print("Python in Html!")<py-script>

Im not sure if it could run modules like Ursina engine ect But what i know is That It allows you to type Python in Html. You can check out its offical Site for more info.我不确定它是否可以运行 Ursina 引擎等模块,但我知道它允许您在 Html 中键入 Python。您可以查看其官方网站以获取更多信息。

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

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