Anaconda 推出了 PyScript,在前端写Python还有多远?

x33g5p2x  于2022-05-23 转载在 Python  
字(4.1k)|赞(0)|评价(0)|浏览(530)

前言

近日,用于科学计算的Python发行版厂商Anaconda发布了PyScript。看完简介Pyscript似乎是跨时代的突破,然而深入研究后发现实现Python前端化编程还任重道远。总体来说,Pyscript属于一次微创新,亮点很多,但基于旧有仍有许多难题需要攻克。Anaconda作为一个大厂,喊出如此振奋人心的slogan,未来的发展仍是十分值得期待。

一、PyScript是什么?

Run Python in Your HTML,Pyscript官网给开发者们描绘出了无比诱人的前景。
这周Pyscript横空出世,几乎席卷了所有前端和Python社区的头条。寥寥几行代码,展现的是一个跨界的突破。

Anaconda 官方对Pyscript提出了很高的期待,Welcome to the world PyScript 文章中对Pyscript做了定义。

Pyscript是一个让用户使用其提供的自定义HTML标签,就可以轻松地在浏览器中运行Python脚本和创建富媒体应用的框架。
[ PyScript is a framework that allows users to run Python and create rich applications in the browser by simply using special HTML tags provided by the framework itself. ]

核心功能包括:
[ Core features include: ]

  • 浏览器中运行Python脚本:插入式标签编程,通过引入外部文件(大多都是来自 Pyodide 项目 的支持, 十分感谢!)进行渲染,应用不依赖服务器端配置。
    [ Python in the browser: Enable drop-in content, external file hosting (made possible by the Pyodide project, thank you!), and application hosting without the reliance on server-side configuration ]
  • 支持Python生态体系:可以运行主流的Python类库和科学技术工具包(比如:numpy, pandas, scikit-learn 等等)
    [ Python ecosystem: Run many popular packages of Python and the scientific stack (such as numpy, pandas, scikit-learn, and more) ]
  • 打通Python和JavaScript壁垒:Python 和JavaScript对象双向通信,共享命名空间。
    [ Python with JavaScript: Bi-directional communication between Python and Javascript objects and namespaces ]
  • 环境配置化: 允许用户在页面代码运行时,自定义引入哪些包和文件。
    [ Environment management: Allow users to define what packages and files to include for the page code to run ]
  • 可视化应用开发:用户可方便使用现成的 UI 组件,如按钮、容器、文本框等等。
    [ Visual application development: Use readily available curated UI components, such as buttons, containers, text boxes, and more ]
  • 可灵活扩展框架:一个可用于直接在 Python 中创建和共享可插拔和可扩展组件的灵活框架。
    [ Flexible framework: A flexible framework that can be leveraged to create and share new pluggable and extensible components directly in Python ]

二、如何使用

1.示例代码

官方提供的hello_world:

  1. <!DOCTYPE html>
  2. <html lang="en">
  3. <head>
  4. <meta charset="utf-8" />
  5. <meta name="viewport" content="width=device-width,initial-scale=1" />
  6. <title>PyScript Hello World</title>
  7. <link rel="icon" type="image/png" href="favicon.png" />
  8. <link rel="stylesheet" href="https://pyscript.net/alpha/pyscript.css" />
  9. <script defer src="https://pyscript.net/alpha/pyscript.js"></script>
  10. </head>
  11. <body>
  12. Hello world! <br>
  13. This is the current date and time, as computed by Python:
  14. <py-script>
  15. from datetime import datetime
  16. now = datetime.now()
  17. now.strftime("%m/%d/%Y, %H:%M:%S")
  18. </py-script>
  19. </body>
  20. </html>

运行结果:

2.数据处理

写一个生成正态分布:

  1. <!DOCTYPE html>
  2. <html lang="en">
  3. <head>
  4. <meta charset="utf-8" />
  5. <meta name="viewport" content="width=device-width,initial-scale=1" />
  6. <title>PyScript Hello World</title>
  7. <link rel="icon" type="image/png" href="favicon.png" />
  8. <link rel="stylesheet" href="https://pyscript.net/alpha/pyscript.css" />
  9. <script defer src="https://pyscript.net/alpha/pyscript.js"></script>
  10. <py-env>
  11. - numpy
  12. </py-env>
  13. </head>
  14. <body>
  15. <py-script>
  16. import numpy as np
  17. result = np.random.normal(0.5, 1, 1000)
  18. for i in result:
  19. print(i)
  20. print(np.mean(result), " ", np.var(result))
  21. </py-script>
  22. </body>
  23. </html>

控制台能看到python的执行日志

对于基础的python操作和类库引入都是可以正常运行。

3.源码剖析

从官方的介绍中,也可以看到Pyscript主要是依赖 Pyodide 项目运行。
这一点 github源码 中也有体现:

  1. loadRuntimes() {
  2. console.log('Initializing runtimes...');
  3. for (const runtime of this.values.runtimes) {
  4. const script = document.createElement('script'); // create a script DOM node
  5. const runtimeSpec = new PyodideRuntime(runtime.src);
  6. script.src = runtime.src; // set its src to the provided URL
  7. script.addEventListener('load', () => {
  8. void runtimeSpec.initialize();
  9. });
  10. document.head.appendChild(script);
  11. }
  12. }

运行前会加载 Pyodide 模块,程序耗时也主要来自这块(严重依赖 pyodide 模块加载速度,官方CDN不太稳定,必要时需要切换CDN

Pyscript相当于封装了一层Pyodide实现,上面Pyscript的数据处理也可以通过以下代码实现

  1. pyodide.runPythonAsync(`
  2. import micropip
  3. await micropip.install('snowballstemmer')
  4. import numpy as np
  5. result = np.random.normal(0.5, 1, 1000)
  6. for i in result:
  7. print(i)
  8. print(np.mean(result), " ", np.var(result))
  9. `);

4.可用类库范围

Pyscript依赖Pyodide的构建库,可用范围还只能满足基本要求,如有定制开发需要私有化部署 Pyodide 版本进行定制式开发。

总结

PyScript 开创式地提供了前端使用Python处理复杂数据的模式,但加载方式和渲染模式还是存在较大改良空间。期待 PyScript 生态圈的后续发展。

相关文章