关于python:分享一个2022年火遍全网的Python框架

最近Python圈子当中进去一个十分火爆的框架PyScript,该框架能够在浏览器中运行Python程序,只须要在HTML程序中增加一些Python代码即可实现。该我的项目进去之后便引起了轰动,马上蹿升到了Github趋势榜榜首,短短20天曾经有10K+的star了。既然如此,小编明天就带大家来看看该框架是如何应用的。

HelloWorld

咱们先来看一下简略的例子,代码如下

<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>

其中Python代码被包裹在了py-script标签外面,而后咱们在浏览器中查看进去的后果,如下所示

要不来画个图

上面这一个例子当中,咱们尝试将matplotlib绘制图表的代码搁置到HTML代码当中去,以实现绘制出一张直方图的操作。首先是matplotlib代码局部,

import matplotlib.pyplot as plt
import numpy as np

np.random.seed(42)
## 随机生成满足正态分布的随机数据
rv = np.random.standard_normal(1000)

fig, ax = plt.subplots()
ax.hist(rv, bins=30)

output

而后咱们将下面的代码搁置到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
    </py-env>
</head>

<body>
<h1>Plotting a histogram of Standard Normal distribution</h1>
<div id="plot"></div>
<py-script output="plot">
    import matplotlib.pyplot as plt
    import numpy as np
    np.random.seed(42)
    rv = np.random.standard_normal(1000)
    fig, ax = plt.subplots()
    ax.hist(rv, bins=30)
    fig
</py-script>
</body>
</html>

output

因为咱们前面须要用到numpymatplotlib两个库,因而咱们通过py-env标签来引进它们,另外

再画个折线图

咱们在下面的根底之上,再来绘制一张折线图,首先咱们再创立一个div标签,外面的idlineplot,代码如下

<div id="lineplot"></div>

同样地在py-script标签中搁置绘制折线图的代码,output对应div标签中的id

<py-script output="lineplot">
.........
</py-script>

绘制折线图的代码如下

import matplotlib.pyplot as plt
fig, ax = plt.subplots()

year1 = [2016, 2017, 2018, 2019, 2020]
population1 = [30, 46, 45, 55, 48]
year2 = [2016, 2017, 2018, 2019, 2020]
population2 = [43, 48, 44, 75, 45]

plt.plot(year1, population1, marker='o', linestyle='--', color='g', label='Countr_1')
plt.plot(year2, population2, marker='d', linestyle='-', color='r', label='Country_2')

plt.xlabel('Year')
plt.ylabel('Population (M)')
plt.title('Year vs Population')
plt.legend(loc='lower right')
fig

output

现阶段运行带有Pyscript的页面加载速度并不会特地地快,该框架刚刚推出,依然处于测试的阶段,前面必定会一直地优化。要是遇到加载速度慢地问题,读者敌人看一下是不是能够通过更换浏览器得以解决。

以上就是本次分享的所有内容,如果你感觉文章还不错,欢送关注公众号:Python编程学习圈,每日干货分享,发送“J”还可支付大量学习材料,内容笼罩Python电子书、教程、数据库编程、Django,爬虫,云计算等等。或是返回编程学习网,理解更多编程技术常识。

评论

发表回复

您的邮箱地址不会被公开。 必填项已用 * 标注

这个站点使用 Akismet 来减少垃圾评论。了解你的评论数据如何被处理