[英]How can I run a Python script in HTML?
您可以使用PHP使用 HTML 運行 Python 文件。
添加一個 PHP 文件作為index.php :
<html>
<head>
<title>Run my Python files</title>
<?PHP
echo shell_exec("python test.py 'parameter1'");
?>
</head>
創建一個 Python 文件作為test.py :
import sys
input=sys.argv[1]
print(input)
打印 PHP 傳遞的參數。
這可能取決於你想做什么。 我個人使用 CGI,如果你從網頁輸入的內容很簡單,它可能會更簡單,而且學習時間更少。 這里有一些資源:
但是,您可能仍需要進行一些配置以允許它運行程序而不是顯示它。
這是一個教程: Apache 教程:使用 CGI 的動態內容
如果您的 Web 服務器是Apache ,您可以使用mod_python模塊來運行您的 Python CGI 腳本。
感謝WebAssembly和Pyodide項目,現在可以在瀏覽器中運行 Python。 看看我的教程。
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>
有一種方法可以用Flask做到這一點!
首先你必須輸入pip install flask
。
您說過,當用戶單擊鏈接時,您希望它執行 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)
您應該使用 Py 代碼,因為它可以運行 html 中的任何 python 腳本,如下所示:
<py-script>print("Python in Html!")<py-script>
我不確定它是否可以運行 Ursina 引擎等模塊,但我知道它允許您在 Html 中鍵入 Python。您可以查看其官方網站以獲取更多信息。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.