pyscript教程--快速上手

5/11/2022 pyscriptpython

不得不佩服一下老美。 pyscript顾名思义,就是在web上写python script,当然JavaScript这个冒牌货是不能和pyscript相比的。

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

首先需要在网页上导入这两个文件,应该一个是加载格式,一个是调用python引擎。

然后就是需要有两个标签,其实也就是类似于vue之类的,有自己专属的标签,在里面写的内容是通过专属js,css进行加载的。

  • <py-script>: can be used to define python code that is executable within the web page. The element itself is not rendered to the page and is only used to add logic
  • <py-repl>: creates a REPL component that is rendered to the page as a code editor and allows users to write executable code

其实除了这两个还有一个标签也需要使用,就是<py-env>这个标签是用来导入库的。

<!DOCTYPE html>

<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>

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

</head>
<py-env>
    - moudle
</py-env>
<body>
    <py-script>
print('hello world')
    </py-script>
</body>
</html>
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22

首先如果需要导入库的话,请在py-env上写上需要导入的库,然后就是py-script标签内的内容,一定要顶格写,然后就是该缩进缩进,跟python正常的语法一个样子。

其实之所以能够使用pyscript,是因为加载的时候,添加了defer,让script延时加载,之后才能正常使用python。

具体的加载记录都卸载了console面板,大家可以去看一下。

<py-script>
print('hello world')
</py-script>
1
2
3

简单写了一个hello world。目前是你需要的库,本地要安装好才能使用,如果本地没有,那么就会报错。

最后放一个数据分析的demo pyscript数据分析

<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="utf-8">
    <link rel="icon" type="image/x-icon" href="./favicon.png">
    <meta name="apple-mobile-web-app-capable" content="yes">
    <meta name="apple-mobile-web-app-status-bar-style" content="default">
    <meta name="theme-color" content="#000000">
    <meta name="name" content="PyScript/Panel Streaming Demo">

    <title>PyScript/Panel Streaming Demo</title>
    <link rel="icon" type="image/x-icon" href="./favicon.ico">

    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/5.15.3/css/all.min.css"
        type="text/css" />
    <link rel="stylesheet" href="https://unpkg.com/@holoviz/panel@0.13.0/dist/css/widgets.css" type="text/css" />
    <link rel="stylesheet" href="https://unpkg.com/@holoviz/panel@0.13.0/dist/css/markdown.css" type="text/css" />

    <script type="text/javascript" src="https://unpkg.com/tabulator-tables@4.9.3/dist/js/tabulator.js"></script>
    <script type="text/javascript" src="https://cdn.bokeh.org/bokeh/release/bokeh-2.4.2.js"></script>
    <script type="text/javascript" src="https://cdn.bokeh.org/bokeh/release/bokeh-widgets-2.4.2.min.js"></script>
    <script type="text/javascript" src="https://cdn.bokeh.org/bokeh/release/bokeh-tables-2.4.2.min.js"></script>
    <script type="text/javascript" src="https://unpkg.com/@holoviz/panel@0.13.0/dist/panel.min.js"></script>
    <script type="text/javascript">
        Bokeh.set_log_level("info");
    </script>

    <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap@4.6.1/dist/css/bootstrap.min.css">
    <link rel="stylesheet" href="https://unpkg.com/@holoviz/panel@0.13.0/dist/bundled/bootstraptemplate/bootstrap.css">
    <link rel="stylesheet" href="https://unpkg.com/@holoviz/panel@0.13.0/dist/bundled/defaulttheme/default.css">

    <script src="https://cdn.jsdelivr.net/npm/jquery@3.5.1/dist/jquery.slim.min.js"></script>
    <script src="https://cdn.jsdelivr.net/npm/bootstrap@4.6.1/dist/js/bootstrap.bundle.min.js"></script>

    <link rel="stylesheet" href="./pyscript.css" />
    <script defer src="./pyscript.js"></script>
</head>

<py-env>
    - bokeh
    - numpy
    - pandas
    - panel
</py-env>

<body>
    <div class="container-fluid d-flex flex-column vh-100 overflow-hidden" id="container">
        <nav class="navbar navbar-expand-md navbar-dark sticky-top shadow" id="header"
            style="background-color: #000000;">
            <button type="button" class="navbar-toggle collapsed" id="sidebarCollapse">
                <span class="navbar-toggler-icon"></span>
            </button>
            <div class="app-header">
                <a class="navbar-brand app-logo" href="/">
                    <img src="./favicon.ico" class="app-logo">
                </a>
                <a class="title" href="" style="color: #f0ab3c;">Panel Streaming Demo</a>
            </div>
        </nav>

        <div class="row overflow-hidden" id="content">
            <div class="col mh-100 float-left" id="main">
                <div class="bk-root" id="controls"></div>
                <div class="row">
                    <div class="bk-root" id="table"></div>
                    <div class="bk-root" id="plot"></div>
                </div>
            </div>
        </div>
    </div>
    <py-script>
import asyncio

import panel as pn
import numpy as np
import pandas as pd

from bokeh.models import ColumnDataSource
from bokeh.plotting import figure
from panel.io.pyodide import show

df = pd.DataFrame(np.random.randn(10, 4), columns=list('ABCD')).cumsum()

rollover = pn.widgets.IntInput(name='Rollover', value=15)
follow = pn.widgets.Checkbox(name='Follow', value=True, align='end')

tabulator = pn.widgets.Tabulator(df, height=450, width=400)

def color_negative_red(val):
    """
    Takes a scalar and returns a string with
    the css property `'color: red'` for negative
    strings, black otherwise.
    """
    color = 'red' if val < 0 else 'green'
    return 'color: %s' % color

tabulator.style.applymap(color_negative_red)

p = figure(height=450, width=600)

cds = ColumnDataSource(data=ColumnDataSource.from_df(df))

p.line('index', 'A', source=cds, line_color='red')
p.line('index', 'B', source=cds, line_color='green')
p.line('index', 'C', source=cds, line_color='blue')
p.line('index', 'D', source=cds, line_color='purple')

def stream():
    data = df.iloc[-1] + np.random.randn(4)
    tabulator.stream(data, rollover=rollover.value, follow=follow.value)
    value = {k: [v] for k, v in tabulator.value.iloc[-1].to_dict().items()}
    value['index'] = [tabulator.value.index[-1]]
    cds.stream(value)

cb = pn.state.add_periodic_callback(stream, 200)

controls = pn.Row(cb.param.period, rollover, follow, width=400)

await show(controls, 'controls')
await show(tabulator, 'table')
await show(p, 'plot')
    </py-script>
    </body>
</html>
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126