当前位置: 首页 > news >正文

折腾笔记[30]-使用bun_python通过javascript优雅调用python库

摘要

使用javascript优雅调用python库.

关键信息

  • bun_python: v0.1.4
  • bun: 1.1.42
  • uv: 0.5.29 (ca73c4754 2025-02-05)
  • python: 3.13

碎碎念

python通过缩进区分代码层级,但是某些网页(Chat)中复制出来的python代码缩进不见了,导致代码运行出错。那么能不能强制Python不使用缩进而是使用大括号(Brace)来区分代码层级呢?直接预处理python代码的方式有:

  1. PyBrace[https://github.com/mayank-verma048/PyBrace]
  2. CurlyPy[https://github.com/DevBoiAgru/CurlyPy]
    但是语法比较古怪而且LLM对这些奇怪语法支持不太好,那么就使用javascript直接调用python的包, 方法有:
  3. bunpy[https://www.npmjs.com/package/bunpy]
  4. deno_python[https://github.com/denosaurs/deno_python]
  5. bun_python[https://github.com/codehz/bun_python]

原理简介

bun_python简介

[https://www.npmjs.com/package/bunpy]
[https://github.com/observerss/python.ts]
[https://github.com/denosaurs/deno_python]
[https://deno.land/x/python@0.4.5]
[https://github.com/codehz/bun_python]
[https://blog.xiaohack.org/4945.html]
This module provides a seamless integration between bun and python by integrating with the Python/C API. It acts as a bridge between the two languages, enabling you to pass data and execute python code from within your bun applications. This enables access to the large and wonderful python ecosystem while remaining native (unlike a runtime like the wondeful pyodide which is compiled to wasm, sandboxed and may not work with all python packages) and simply using the existing python installation.

import { python } from "bun_python";const np = python.import("numpy");
const plt = python.import("matplotlib.pyplot");const xpoints = np.array([1, 8]);
const ypoints = np.array([3, 10]);plt.plot(xpoints, ypoints);
plt.show();

Since Bun provides a plugin API, it can extend the import behavior at runtime. We have also made a bun plugin for it, which allows you to import python modules using something like import * as np from "python:numpy". Unfortunately, there is currently no way to directly make the bun use the preload script from npm, so you have to manually create a preload script to load the python plugin.

Setup:

Create a file named preload.ts:
preload.ts

import "bun_python/plugin.ts"

Setup bunfig.toml
bunfig.toml

preload = ["./preload.ts"]

示例:

import * as np from 'python:numpy';
import * as plt from 'python:matplotlib.pyplot';const xpoints = np.array([1, 8]);
const ypoints = np.array([3, 10]);plt.plot(xpoints, ypoints);
plt.show();

This module uses FFI to interface with the Python interpreter's C API. So you must have an existing Python installation (with the shared library), which is something like python310.dll, etc.

Python installed from Microsoft Store does not work, as it does not contain shared library for interfacing with Python interpreter.

If the module fails to find Python, you can add the path to the Python in the BUN_PYTHON_PATH environment variable.

BUN_PYTHON_PATH if set, must point to full path including the file name of the Python dynamic library, which is like python310.dll (Windows), libpython310.dylib (macOS) and libpython310.so (Linux) depending on platform.

CurlyPy简介

[https://github.com/DevBoiAgru/CurlyPy]
PyBrace作为Python的扩展,允许开发者使用花括号来定义代码块,而不是依靠空格或制表符的缩进。
CurlyPy is a preprocessor that translates Python code written using curly braces ({}) into standard Python, making indentation obsolete. It provides the flexibility to use semicolons (😉 as optional statement separators, making Python syntax more familiar to developers accustomed to languages like C, Java, or JavaScript.

With CurlyPy, you can write Python code using braces to define code blocks, eliminating the need for indentation while still retaining Python's powerful features.

Curly Braces for Code Blocks: Use {} to denote the start and end of code blocks, removing the need for indentation.
Semi-Mandatory Semicolons: Semicolons (😉 are supported as optional separators between statements, but they are still not strictly required after every statement. They will, however, be required if you are writing multiple instructions in the same line.
Flexible Syntax: Write Python code with a more structured format, closer to languages like C, Java, or JavaScript, while keeping all the strengths of Python.
Compatible with Python: CurlyPy preprocesses your code into standard Python, so it can be executed by any Python interpreter.
Dictionary and Set Types: The standard Python dictionary and set types are available in CurlyPy, using type hints.

Once you have CurlyPy installed, you can preprocess your Python files written with curly braces and optional semicolons into standard Python.

uv add curlypy
uv run curlypy hello.cpy

示例:

def HelloWorld(name: str) {if name {print (f"Hello {name}!");}else {print ("Hello World!");}
}

实践

Import any locally installed Python package, for example, matplotlib:
代码:

import { python } from "bun_python";const np = python.import("numpy");
const plt = python.import("matplotlib.pyplot");const xpoints = np.array([1, 8]);
const ypoints = np.array([3, 10]);plt.plot(xpoints, ypoints);
// plt.show();
console.log(xpoints,ypoints);

命令:

bun init
bun install bun_python
bun run numpy_test.js

效果

[1 8] [ 3 10]
http://www.wuyegushi.com/news/351.html

相关文章:

  • Linux系统目录结构完全指南:目录与文件夹的本质区别
  • 【2025最新】官方Claude API中转服务 | 快速接入Claude 4 API | 国内Claude API接口中转指南
  • 基于Qt封装tomlplusplus得到读写键值对的库
  • AT_abc396_c [ABC396C] Buy Balls 题解
  • [ABC394D] Colorful Bracket Sequence 题解
  • K8S
  • Redis桌面管理工具Another-Redis-Desktop-Manager 1.3.7 安装全流程
  • 1
  • 创建【网络连接】的快捷方式
  • 线性代数
  • 12 MCP Servers的介绍
  • 500部迪士尼电影下载推荐_迪士尼动画大全列表必看网盘分享
  • 点分治
  • 华为荣耀手机还原主屏幕布局
  • ESP IDF引入外部资源文件
  • Day11 矩阵乘法 dp、*常系数齐次线性递推、*动态 dp
  • 亿邮相关漏洞总结
  • 使用DFU模式快速重装macOS15到macbook
  • 大模型的JSON之殇:从脆弱的API调用到稳健的未来
  • [20250727]数论基本概念、最大公约数
  • day05
  • 读心与芯:我们与机器人的无限未来06问题或方案
  • 使用Vue.js实现表单验证
  • HackerOne漏洞报告:AddTagToAssets操作中的IDOR漏洞分析
  • 2025.7 广大附中集训游记
  • Cursor 远程主机无法下载 Python 插件解决
  • Cursor 远程 SSH 主机无法下载插件解决
  • 图灵奖和诺贝尔奖双料得主、AI教父Hinton教授国内首次演讲PPT全文实录
  • Chiplet封装技术全面介绍
  • HTTP响应处理的灵活设计(3844)