分享一個(gè)2022年火遍全網(wǎng)的Python框架
最近Python圈子當(dāng)中出來(lái)一個(gè)非?;鸨目蚣躊yScript,該框架可以在瀏覽器中運(yùn)行Python程序,只需要在HTML程序中添加一些Python代碼即可實(shí)現(xiàn)。該項(xiàng)目出來(lái)之后便引起了轟動(dòng),馬上躥升到了Github趨勢(shì)榜榜首,短短20天已經(jīng)有10K+的star了。既然如此,小編今天就帶大家來(lái)看看該框架是如何使用的。
HelloWorld
我們先來(lái)看一下簡(jiǎn)單的例子,代碼如下:
<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標(biāo)簽里面,然后我們?cè)跒g覽器中查看出來(lái)的結(jié)果,如下所示:
要不來(lái)畫個(gè)圖
下面這一個(gè)例子當(dāng)中,我們嘗試將matplotlib繪制圖表的代碼放置到HTML代碼當(dāng)中去,以實(shí)現(xiàn)繪制出一張直方圖的操作。首先是matplotlib代碼部分,
import matplotlib.pyplot as plt
import numpy as np
np.random.seed(42)
## 隨機(jī)生成滿足正態(tài)分布的隨機(jī)數(shù)據(jù)
rv = np.random.standard_normal(1000)
fig, ax = plt.subplots()
ax.hist(rv, bins=30)
output:
然后我們將上面的代碼放置到HTML代碼當(dāng)中去,代碼如下:
<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:
由于我們后面需要用到numpy和matplotlib兩個(gè)庫(kù),因此我們通過(guò)py-env標(biāo)簽來(lái)引進(jìn)它們,另外
再畫個(gè)折線圖
我們?cè)谏厦娴幕A(chǔ)之上,再來(lái)繪制一張折線圖,首先我們?cè)賱?chuàng)建一個(gè)div標(biāo)簽,里面的id是lineplot,代碼如下:
<div id="lineplot"></div>
同樣地在py-script標(biāo)簽中放置繪制折線圖的代碼,output對(duì)應(yīng)div標(biāo)簽中的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:
現(xiàn)階段運(yùn)行帶有Pyscript的頁(yè)面加載速度并不會(huì)特別地快,該框架剛剛推出,仍然處于測(cè)試的階段,后面肯定會(huì)不斷地優(yōu)化。要是遇到加載速度慢地問(wèn)題,讀者朋友看一下是不是可以通過(guò)更換瀏覽器得以解決。