易妖游戏网
您的当前位置:首页在网页上跑个 python 程序 - 试水 pyscript

在网页上跑个 python 程序 - 试水 pyscript

来源:易妖游戏网


前言。

早上刚看到资讯,说可以在网页上跑 python 程序了。那我就来试试水,跑个例子。


一、PyScript 是什么?

二、使用步骤

1.CDN

因为只是试水,这里我使用CDN来安装 PyScript。

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

在html文件中引入CDN。

2.第一个 PyScript 应用

可以使用vscode + 来运行。

<!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">
    <!-- 引入 PyScript -->
    <link rel="stylesheet" href="https://pyscript.net/alpha/pyscript.css" />
    <script defer src="https://pyscript.net/alpha/pyscript.js"></script>

    <title>First PyScript Application</title>
    <style>
        py-script {
            width: 100%;
            height: 100%;
            font-size: 20px;
            text-align: center;
            position: absolute;
        }
    </style>
</head>

<body>
    <py-script>
        print('Hello PyScript!')
    </py-script>

</body>

</html>

3. 使用第三方包

千万不要格式化代码。

<!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">
    <!-- 引入 PyScript -->
    <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>

    <title>First PyScript Application</title>
    <style>
        py-script {
            width: 100%;
            height: 100%;
            font-size: 20px;
            text-align: center;
            position: absolute;
        }
    </style>
</head>

<body>
    <table>
        <tr>
            <th>Sin(x)</th>
            <th>Cos(x)</th>
        </tr>
        <tr>
            <td>
                <div id="Sin"></div>
            </td>
            <td>
                <div id="Cos"></div>
            </td>
        </tr>
    </table>
    <py-script output="Sin">
import matplotlib.pyplot as plt
import numpy as np

x = np.arange(-np.pi, np.pi,np.pi/180)
y = np.sin(x)

fig, ax = plt.subplots()
ax.plot(x, y)
fig
    </py-script>
    <py-script output="Cos">
import matplotlib.pyplot as plt
import numpy as np

x = np.arange(-np.pi, np.pi,np.pi/180)
y = np.cos(x)

fig, ax = plt.subplots()
ax.plot(x, y)
fig
    </py-script>

</body>

</html>

总结

只能说现在可以运行,但是坑还是很多。也没有像样的代码提示和语法高亮。而且速度也是一如既往的感人。。。期待以后会变得更好吧,到这里也就结束了,喜欢的话点个赞。

因篇幅问题不能全部显示,请点此查看更多更全内容