在网页中执行python

背景:

在网页中执行python,脚本,也就是在html中写python,或者引入python脚本代码

方法:

也就引入pyscript库,调用python脚本

步骤

1、新建一个html文件testpyscript.html

<html>
    <head>
      <link rel="stylesheet" href="https://pyscript.net/alpha/pyscript.css" />
      <script defer src="https://pyscript.net/alpha/pyscript.js"></script>
      <py-env>
        - numpy
        - matplotlib
        - paths:
          - ./data.py
      </py-env>
    </head>

  <body>
    <h1>Let's plot random numbers</h1>
    <div id="plot"></div>
    <py-script output="plot">
    import matplotlib.pyplot as plt
    from data import make_x_and_y

    x, y = make_x_and_y(n=1000)

    fig, ax = plt.subplots()
    ax.scatter(x, y)
    fig
    </py-script>
  </body>
</html>
# data.py
import numpy as np

def make_x_and_y(n):
    x = np.random.randn(n)
    y = np.random.randn(n)
    return x, y

2、在这testpyscript.html和data.py文件目录下执行终端,也就命令行(windows)

python -m http.server 8080 –bind 127.0.0.1

3、127.0.0.1:8080/testpyscript.html

文章出处登录后可见!

已经登录?立即刷新

共计人评分,平均

到目前为止还没有投票!成为第一位评论此文章。

(0)
xiaoxingxing的头像xiaoxingxing管理团队
上一篇 2023年11月6日
下一篇 2023年11月6日

相关推荐