zl程序教程

您现在的位置是:首页 >  后端

当前栏目

在网页中撰写Python程式 - 使用pyscript

Python网页 撰写 使用
2023-09-14 09:12:58 时间

在网页中撰写Python程式 - 使用pyscript

根据 Anaconda 的项目 pyscript,可以将 python 的代码直接写在网页中,目前只支援两种标签,分别是<py-script><py-repl>,以下是简单的示例。

使用这两行导入 pyscript

<link rel="stylesheet" href="https://pyscript.net/alpha/pyscript.css" />
<script defer src="https://pyscript.net/alpha/pyscript.js"></script>

使用<py-repl>标签,会显示原始码,可以单击左下角的按键,开始运行。

<py-repl>
from datetime import datetime
now = datetime.now()
print("目前日期时间", now.strftime("%m/%d/%Y, %H:%M:%S"))

list1 = list("Pythony在网页中执行")
for i in list1:
	print("{}".format(i))
</py-repl> 

效果如下:

在这里插入图片描述
使用<py-repl>标签的结果,原则上是使用非同步处理,所以与主画面渲染比较会有延迟。

使用<py-script>标签

<py-script>
from datetime import datetime
now = datetime.now()
print("目前日期时间", now.strftime("%m/%d/%Y, %H:%M:%S"))

list1 = list("Pythony在网页中执行")
for i in list1:
	print("{}".format(i))
</py-script> 

效果如下:
在这里插入图片描述

使用<py-script>标签的结果

完整程式范例如下。

<!DOCTYPE html>
<html>
  <head>
    <meta charset="utf-8" />
    <meta name="viewport" content="width=device-width,initial-scale=1" />

    <title>第一个 PyScript 练习</title>

    <link rel="icon" type="image/png" href="favicon.png" />
		<link rel="stylesheet" href="https://pyscript.net/alpha/pyscript.css" />
		<script defer src="https://pyscript.net/alpha/pyscript.js"></script>
  </head>

  <body>
    在网页中撰写 Python 程式<br>
    显示目前时间与印出一个列表:
使用 py-repl 标签<br/>
    <py-repl>
from datetime import datetime
now = datetime.now()
print("目前日期时间", now.strftime("%m/%d/%Y, %H:%M:%S"))

list1 = list("Pythony在网页中执行")
for i in list1:
	print("{}".format(i))
    </py-repl> 
    
使用 py-script 标签<br/>
    <py-script>
from datetime import datetime
now = datetime.now()
print("目前日期时间", now.strftime("%m/%d/%Y, %H:%M:%S"))

list1 = list("Pythony在网页中执行")
for i in list1:
	print("{}".format(i))
    </py-script>
  </body>
</html>

参考资料

  • pyscript,https://pyscript.net/
  • PyScript,https://github.com/pyscript/pyscript