摘要
使用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代码的方式有:
- PyBrace[https://github.com/mayank-verma048/PyBrace]
- CurlyPy[https://github.com/DevBoiAgru/CurlyPy]
但是语法比较古怪而且LLM对这些奇怪语法支持不太好,那么就使用javascript直接调用python的包, 方法有: - bunpy[https://www.npmjs.com/package/bunpy]
- deno_python[https://github.com/denosaurs/deno_python]
- 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]