py-scripts初体验

语雀原文地址: py-scripts初体验

参考资料

PyScript: Python in the Browser 官网

pyscript 独立官网

py-scripts官方github仓库

简介

py-scripts是anaconda团队开发的浏览器中的python运行环境, 基于Pyodide(一个将CPython编译成WebAssembly的项目).

如何使用

hello-wrold

  • 引入依赖:
<link rel="stylesheet" href="https://pyscript.net/alpha/pyscript.css" />
<script defer src="https://pyscript.net/alpha/pyscript.js"></script>
  • <py-scripts>标签中写代码
<html>
  <head>
    <link rel="stylesheet" href="https://pyscript.net/alpha/pyscript.css" />
    <script defer src="https://pyscript.net/alpha/pyscript.js"></script>
  </head>
  <body> <py-script> print('Hello, World!') </py-script> </body>
</html>

image.png

计算圆周率

<html>
  <head>
    <link rel="stylesheet" href="https://pyscript.net/alpha/pyscript.css" />
    <script defer src="https://pyscript.net/alpha/pyscript.js"></script>
  </head>
  <body>
      <py-script>
print("计算圆周率:")
def wallis(n):
    pi = 2
    for i in range(1,n):
        pi *= 4 * i ** 2 / (4 * i ** 2 - 1)
    return pi

pi = wallis(10000000)
s = f"圆周率接近: {pi:.10f}"
print(s)
      </py-script>
  </body>

image.png

结合d3.js画图

<html>
  <head>
    <title>d3: JavaScript & PyScript visualizations side-by-side</title>
    <meta charset="utf-8">

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


    <style>
    .loading {
      display: inline-block;
      width: 50px;
      height: 50px;
      border: 3px solid rgba(255, 255, 255, 0.3);
      border-radius: 50%;
      border-top-color: black;
      animation: spin 1s ease-in-out infinite;
    }

    @keyframes spin {
      to {
        transform: rotate(360deg);
      }
    }
    </style>

    </head>
    <body>
      <b>
        Based on <i><a href="https://observablehq.com/@d3/learn-d3-shapes?collection=@d3/learn-d3>">Learn D3: Shapes</a></i> tutorial.
      </b>
      <div style="display: flex; flex-direction: row">
        <div>
          <div style="text-align: center">JavaScript version</div>
          <div id="js" style="width: 400px; height: 400px">
            <div class="loading"></div>
          </div>
        </div>
        <div>
          <div style="text-align: center">PyScript version</div>
          <div id="py" style="width: 400px; height: 400px">
            <div class="loading"></div>
          </div>
        </div>
      </div>

<script type="importmap">
{
  "imports": {
    "d3": "https://cdn.skypack.dev/d3@7"
  }
}
</script>

<script type="module">
import * as d3 from "d3"

const fruits = [
  {name: "🍊", count: 21},
  {name: "🍇", count: 13},
  {name: "🍏", count: 8},
  {name: "🍌", count: 5},
  {name: "🍐", count: 3},
  {name: "🍋", count: 2},
  {name: "🍎", count: 1},
  {name: "🍉", count: 1},
]

const fn = (d) => d.count
const data = d3.pie().value(fn)(fruits)

const arc = d3.arc()
  .innerRadius(210)
  .outerRadius(310)
  .padRadius(300)
  .padAngle(2 / 300)
  .cornerRadius(8)

const js = d3.select("#js")
js.select(".loading").remove()

const svg = js
  .append("svg")
  .attr("viewBox", "-320 -320 640 640")
  .attr("width", "400")
  .attr("height", "400")

for (const d of data) {
  svg.append("path")
    .style("fill", "steelblue")
    .attr("d", arc(d))

  const text = svg.append("text")
    .style("fill", "white")
    .attr("transform", `translate(${arc.centroid(d).join(",")})`)
    .attr("text-anchor", "middle")

  text.append("tspan")
    .style("font-size", "24")
    .attr("x", "0").text(d.data.name)

  text.append("tspan")
    .style("font-size", "18")
    .attr("x", "0")
    .attr("dy", "1.3em")
    .text(d.value)
}
</script>

<py-script>
from pyodide import create_proxy, to_js
import d3

fruits = [
  dict(name="🍊", count=21),
  dict(name="🍇", count=13),
  dict(name="🍏", count=8),
  dict(name="🍌", count=5),
  dict(name="🍐", count=3),
  dict(name="🍋", count=2),
  dict(name="🍎", count=1),
  dict(name="🍉", count=1),
]

fn = create_proxy(lambda d, *_: d["count"])
data = d3.pie().value(fn)(to_js(fruits))

arc = (d3.arc()
  .innerRadius(210)
  .outerRadius(310)
  .padRadius(300)
  .padAngle(2 / 300)
  .cornerRadius(8))

py = d3.select("#py")
py.select(".loading").remove()

svg = (py
  .append("svg")
  .attr("viewBox", "-320 -320 640 640")
  .attr("width", "400")
  .attr("height", "400"))

for d in data:
  d_py = d.to_py()

  (svg.append("path")
    .style("fill", "steelblue")
    .attr("d", arc(d)))

  text = (svg.append("text")
    .style("fill", "white")
    .attr("transform", f"translate({arc.centroid(d).join(',')})")
    .attr("text-anchor", "middle"))

  (text.append("tspan")
    .style("font-size", "24")
    .attr("x", "0")
    .text(d_py["data"]["name"]))

  (text.append("tspan")
    .style("font-size", "18")
    .attr("x", "0")
    .attr("dy", "1.3em")
    .text(d_py["value"]))
</py-script>

</body>
</html>

image.png

结论

  • 非常有趣
  • 非常早期, 官网连hello-world教程都没有
  • wasm数据过大, 加载了几分钟还没加载出来, 毕竟是要把整个编译器加载到浏览器中, 而且这个wasm没有放到国内的cdn上.(所以近期的玩法, 最大的可能是将这些文件放到本地…)
  • 未来给pythoner带来更多可能, 结合jupter-notebook可以带来很多炫酷的玩法.
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值