我有一个名为
main.py
的 Python 文件,我想在我正在创建的网站中按下按钮时运行该文件,但我不确定如何执行此操作。我在 PyScript 网站上查看了几个不同的示例,但似乎没有什么是我想要的。有可能吗?如果可以的话我该怎么做?
HTML代码:
<!DOCTYPE html>
<html>
<head>
<title>Secure Login</title>
<link rel="stylesheet"
href="style.css">
<link rel=”stylesheet” href=”htpps://pyscript.net/alpha/pyscript.css” />
<script defer
src=”htpps://pyscript.net/alpha/pyscript.js”>
</script>
</head>
<body>
<div class="main">
<h1>Secure Login</h1>
<h3>Enter your login credentials</h3>
<p>Not registered?
<a href="#"
style="text-decoration: none;">
Create an account
</a>
</p>
</div>
</body>
</html>
<script>
function runpython() {
<py-script src=”/my_own_file.py”>
</py-script>
}
</script>
<button onclick="runpython()">please work</button>
(您使用的是相当旧的 PyScript 版本 -
alpha
在撰写本文时已经有两年了!以下内容是使用最新版本 2024.4.1
编写的。)
通常,当您触发事件时,您将在文件中执行一个函数,使用pyscript.when
真的需要执行整个文件,我认为最接近的是:
<link rel="stylesheet" href="https://pyscript.net/releases/2024.4.1/core.css">
<script type="module" src="https://pyscript.net/releases/2024.4.1/core.js"></script>
<button id="run">Run main.py</button>
<py-config>
[files]
"main.py" = "main.py"
</py-config>
<script type="py">
from pyscript import when
@when('click', '#run')
def run_main(evt):
with open("main.py") as f:
exec(f.read())
</script>