• 首页 首页 icon
  • 工具库 工具库 icon
    • IP查询 IP查询 icon
  • 内容库 内容库 icon
    • 快讯库 快讯库 icon
    • 精品库 精品库 icon
    • 问答库 问答库 icon
  • 更多 更多 icon
    • 服务条款 服务条款 icon

在本机执行 pyscript 在网页执行python

武飞扬头像
Yehchitsai
帮助6

如何在本机执行 pyscript (在网页中执行python)

pyscript可以让使用者在 H5 的网页中执行 python 的语法,目前只是alpha版本,如果透过官方网站执行,速度会很慢,还有可能因为国外网站的关系,导致无法正常运行,所以建议下载 github 的 pyscript 的原始代码,透过Node.js 进行本地端的安装。

下载 pyscript

  1. 直接到 pyscript 的github官网下载 https://github.com/pyscript/pyscript

学新通
将下载下来 pyscript-main.zip 的压缩档放在一个新建的文件夹中,比方说 localPyScript

安装Node.js

  1. 下载并安装Node.js,https://nodejs.org/,这部份就不多说了。

安装 rollup 包

  1. 全局安装 rollup
# 查看当前使用的镜像地址,通常是 https://registry.npmjs.org
npm config get registry
# 将镜像地址切换为淘宝镜像,加快安装速度
npm config set registry https://registry.npm.taobao.org
npm install --global rollup

解压缩 pyscript 项目

  1. 解压缩 pyscript-main.zip,并切换到 pyscriptjs 文件夹,并进行安装相关套件。
cd pyscriptjs
npm install

学新通

执行 node 服务器

  1. 执行 node 服务器,它会在 examples/build 文件夹中生成需要的 jscss 文件
npm run dev

学新通

练习用网页

  1. 建立一个简单的练习用网页 hello_world.html,记得要放在examples 文件夹中,如下图所示。

学新通

代码如下,记得设定 pyscript.css 与 pyscript.js 设定为本机端 (http://localhost:8080/build/)。

<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="utf-8" />
    <meta name="viewport" content="width=device-width,initial-scale=1" />

    <title>PyScript Hello World</title>
<!-- 这里要特别注意,要进行修改的 -->
    <link rel="stylesheet" href="http://localhost:8080/build/pyscript.css" />
    <script defer src="http://localhost:8080/build/pyscript.js"></script>
  </head>

  <body>
    Hello world! <br>
    This is the current date and time, as computed by Python:
    <py-script>
from datetime import datetime
now = datetime.now()
now.strftime("%m/%d/%Y, %H:%M:%S")
    </py-script>
  </body>
</html>
学新通

修改 pyscript.js,变更 pyodide.js 的存取位置

  1. 变更 pyodide.js 的存取位置,pyodide是最主要提供能在网页上执行 python 的主要套件,但是因为系统预设使用 https://cdn.jsdelivr.net 這個CDN 服务,但自从 2021 年后 jsdelivr 已经不能在中国内使用,所以需要将存取位置改为 https://pyodide-cdn2.iodide.io。

打开 ./pyscriptjs/examples/build/pyscript.js 文件,修改内容如下,并储存。

const DEFAULT_RUNTIME = {
//src: ‘https://cdn.jsdelivr.net/pyodide/v0.20.0/full/pyodide.js’,
src: ‘https://pyodide-cdn2.iodide.io/v0.20.0/full/pyodide.js’,
name: ‘pyodide-default’,
lang: ‘python’,
};
let appConfig_ = {
autoclose_loader: true,
};

学新通

打开网页检视结果

8.打开网页输入 http://localhost:8080/hello_world.html 就可以检视结果了。

学新通

最终文件夹说明

pyscript 项目解压缩后的目录结构如下图所示,而我们所有的操作都在 pyscripts 这个文件夹中,当整个服务器运行起来时,是以 pyscripts\examples 为网页服务器的根目录,特别提醒一下,其实 examples 有很多示例可以参考,可以把 examples 中的示例搬到pyscripts\examples,只要修改 pyscript.css 与 pyscript.js 设定为本机端,就可以运行了。

学新通
这是内附的范例。
学新通

下图是我们这个项目需要修改的文件,pyscript.js 是主要的js执行文件,其中会使用到 pyodide 的功能,所以需要调整网址;hello_world.html 是我们新增的文件,用来展示pyscript的功能。
学新通

参考资料

  • pyscript,https://pyscript.net/
  • PyScript,https://github.com/pyscript/pyscript

这篇好文章是转载于:学新通技术网

  • 版权申明: 本站部分内容来自互联网,仅供学习及演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,请提供相关证据及您的身份证明,我们将在收到邮件后48小时内删除。
  • 本站站名: 学新通技术网
  • 本文地址: /boutique/detail/tanhficjfb
系列文章
更多 icon
同类精品
更多 icon
继续加载