Python MOD
用 Python 编写 Minecraft 模组。
Python MOD 是一个 Fabric 模组,它将真实的 Python 3 运行时嵌入到 Minecraft
中,并提供一个沙盒 API 用于注册内容、挂钩游戏事件以及构建屏幕。只需将 .pymod 文件放入文件夹,重启游戏,你的 Python
代码即可在-game 内运行——无需 Java,无需 Gradle,无需重新编译。
- Minecraft 1.21.1 · Fabric Loader 0.16+ · Fabric API
- 运行时:GraalPy 24.2.2(兼容 CPython 3.11)
- API 级别:1
- 许可证:可用许可证 — © 2026 kscm · 项目所有者:kscm
Hello, world
hello_world.pymod 是一个包含两个文件的 zip 包:
hello_world.pymod
├── pymod.json
└── src/
└── main.py
pymod.json
{
"id": "hello_world",
"name": "Hello World",
"version": "1.0.0",
"api_version": 1,
"entrypoint": "src/main.py",
"permissions": []
}
src/main.py
import pythonmod
from pythonmod import registry, events
registry.block("hello_block", hardness=1.0, sounds="wood", name="Hello Block")
@events.player_join
def greet(player):
player.send_message("Hello from Python!")
将其放入 .minecraft/mods/pythonmods/ 目录,启动游戏,按 P 键。
API 涵盖的功能
pythonmod.registry — 内容
| 函数 |
注册 |
block(id, hardness, resistance, requires_tool, luminance, sounds, group, item, texture, name) |
完整立方体方块,可选附带方块物品 |
item(id, max_stack, group, texture, name) |
普通物品 |
food(id, nutrition, saturation, always_edible, max_stack, group, texture, name) |
可食用物品 |
所有内容都位于你的模块 ID 命名空间下,因此在一个 "id": "gems" 的包中调用 block("ruby_ore") 会成为 gems:ruby_ore。两个不相关的包可以各自定义 ruby_ore 而永远不会发生冲突。
模型和英文名称会自动生成到一个名为 PythonMOD Generated 的资源包中,因此即使你还没有绘制任何纹理,新内容也可以使用。
pythonmod.events — 游戏挂钩
| 事件 |
参数 |
server_tick |
(server) |
server_started / server_stopping |
(server) |
player_join / player_leave |
(player) |
block_break |
(player, pos, block) |
block_use |
(player, pos) |
item_use |
(player) |
client_tick |
(client) |
from pythonmod import events
@events.block_break
def on_break(player, pos, block):
player.send_actionbar("broke %s at %d,%d,%d" % (block.id(), pos.x(), pos.y(), pos.z()))
如果事件名称无法识别,将在订阅时引发异常。由于静默永不触发的事件是最昂贵的拼写错误类型,因此不允许这种情况发生。
pythonmod.gui — 屏幕
from pythonmod import gui
(gui.screen("Ore Scanner")
.size(280, 160)
.label("Radius", 20, 34)
.slider("blocks", 20, 48, 240, value=16, min=4, max=64, on_change=set_radius)
.checkbox("Include deepslate", 20, 80, checked=True, on_change=set_deepslate)
.button("Scan", 20, 110, 240, 20, on_click=scan)
.open())
坐标是相对于面板的,并且面板已自动居中。内置了亮色和暗色调色板,并遵循玩家的设置——脚本从不手动选择颜色。
在专用服务器上,没有客户端,因此 open() 返回 False 并记录警告而不是抛出异常。当包旨在同时在两端运行时,请使用 gui.available() 进行保护。
pythonmod.xmlgui — 声明式 HUD(XML)
在 gui/*.xml 中声明一个游戏内 HUD 面板——无需 Python 屏幕代码。每个模块的 gui/ 文件夹会在加载时自动扫描。
gui/hud.xml
<gui>
<screen id="hud_demo" show_page="hud" x="12" y="12">
<label id="title" text="Python MOD · XML HUD" x="0" y="0"
style="color:#1b1f24" style_dark="color:#eceff3"/>
<divider x="0" y="20" w="180"/>
<button id="mine" text="Mine +1" x="0" y="30" w="160" h="20"
style="bg:#1565c0;color:#ffffff" style_dark="bg:#5fa8ff;color:#0b0e12"
click_script="on_click.py" follow_script="after.py"/>
<checkbox id="auto" text="Auto mine" x="0" y="58" checked="true"
style="color:#1b1f24" style_dark="color:#eceff3"
click_script="on_toggle.py"/>
<slider id="speed" text="Speed" x="0" y="84" w="180" value="0.5" min="0" max="1"/>
<text_field id="status" placeholder="Status: ready" x="0" y="110" w="180" h="20"/>
</screen>
</gui>
| 属性 |
适用对象 |
含义 |
style / style_dark |
控件 |
类似 CSS 的 key:value 对(color, bg, border)。活动的亮色/暗色主题会选择其中一个 |
click_script |
按钮, 复选框 |
点击控件时运行的 Python 文件 |
follow_script |
按钮 |
紧接在 click_script 完成后运行的 Python 文件 |
show_page |
屏幕 |
显示位置:hud(游戏内叠加层)。screen / main_menu 保留供其他用途 |
x / y |
屏幕, 控件 |
GUI 像素中的坐标;屏幕是面板锚点,控件是相对于它的 |
脚本在隔离上下文中运行——拥有与模块相同的权限和沙箱,但崩溃只会禁用该脚本,而不会导致整个模块失效。它们可以像其他代码一样 import pythonmod。点击的按钮会先运行 click_script,然后运行 follow_script;从 Python 也可以访问相同的路径:
from pythonmod import xmlgui
xmlgui.trigger("hud_demo", "mine") # 运行 on_click.py 然后 after.py
请参阅 examples/xml_hud_demo/ 以获取完整的、可运行的面板示例(包含带有亮色/暗色样式和 Python 脚本的按钮、复选框、滑块和文本字段)。
清单
| 字段 |
是否必需 |
备注 |
id |
是 |
2–64 个字符,仅限 a-z、0-9、_。将成为你的注册表命名空间 |
version |
是 |
自由格式 |
api_version |
是 |
必须为 1。参见下方的 Attribution(署名)部分 |
name |
否 |
默认为 id |
description |
否 |
显示在管理器界面中 |
authors |
否 |
字符串数组 |
entrypoint |
否 |
默认为 src/main.py |
environment |
否 |
*、client 或 server |
permissions |
否 |
见下表 |
权限
| 权限 |
风险等级 |
授予内容 |
file_read |
低 |
读取自身数据文件夹内的文件 |
file_write |
中 |
写入自身数据文件夹内的文件 |
network |
高 |
出站网络连接 |
thread |
高 |
创建线程 |
native |
严重 |
原生/JNI 访问 —— 实质上无沙箱限制 |
process |
严重 |
生成进程 —— 实质上无沙箱限制 |
无论授予何种权限,沙箱都将文件访问范围限制在 pythonmod/data/<your-id>/ 内。调用 pythonmod.data_path("state.json") 会构建一个合法路径;任何超出该树结构的路径在到达文件系统之前都会被拒绝。
请求 native 或 process 权限的包会在日志中产生醒目的警告,并在管理器界面中以红色条目显示。这是有意为之:这两个权限赋予了脚本与 Java 模组同等的权力。
游戏内管理器
按 P(可重新绑定)打开:
- 已加载的内容、失败的内容及确切原因
- 每个包注册的内容及其耗时
- 被授予的权限,按风险等级着色
- 最近打印的几行输出
- light / dark / auto(浅色/深色/自动)主题切换,并保存至配置文件
配置
.minecraft/config/pythonmod.json
| 键 |
默认值 |
含义 |
enabled |
true |
总开关 |
autoDownloadRuntime |
true |
首次启动时获取 GraalPy |
mavenRepository |
Maven Central |
用于下载的镜像源 |
verifyChecksums |
true |
验证每个下载的 jar 文件 |
theme |
"auto" |
auto、light 或 dark |
callbackTimeoutMs |
5000 |
超过此时间的回调将禁用其所属包 |
verboseLogging |
false |
额外诊断信息 |
工作原理
preLaunch RuntimeProvisioner 下载 GraalPy,验证 SHA-1,
将其注入 Knot 类加载器
↓
main PythonEngine 一个共享引擎
SandboxPolicy 每个包一个上下文,拥有独立的
权限集和虚拟文件系统
PyModLoader 扫描 → 验证 → 解压 → 运行
PyBridge Python 可访问的唯一 Java 对象
↓
runtime PyEventBridge Fabric 回调分发至 Python 钩子
PyGuiBridge 屏幕描述,在客户端渲染
XmlHudRenderer XML 声明的 HUD 面板,从 gui/*.xml 扫描
XmlGuiBridge 触发小部件的点击/跟随脚本
运行时未捆绑。 GraalPy 大约 200 MB —— 比大多数整合包都大。它仅在首次启动时下载一次,经过校验和验证后,缓存在 .minecraft/pythonmod/runtime/ 中。如果下载失败,游戏仍可启动;Python 支持仅报告为不可用。
每个包一个上下文,而非共享一个上下文。 多语言上下文无法持有两套不同的权限集,因此共享上下文会将所有包的权限取并集——如果一个包请求了 network,就会静默地将网络访问权授予其他所有包。独立的上下文还意味着崩溃的包可以单独禁用。
Guest 异常永不逃逸。 每次对 Python 的调用都通过 PythonEngine.invoke,它会捕获 Guest 异常,打印 Python 堆栈跟踪,并禁用出错的包。脚本中的拼写错误不允许导致服务器宕机。
构建
需要 JDK 21。本地 Temurin 21 位于 .tooling/jdk-21;如果你更喜欢使用其他版本,可以在 gradle.properties 中自行设置 org.gradle.java.home。
./gradlew build # 构建模组 jar
./gradlew packExamples # 将 examples/ 打包为 build/pymods/*.pymod
署名
Python MOD 根据 Available License(参见 LICENSE)分发,
© 2026 kscm,项目所有者 kscm。
第 6 条 要求使用此 API 的软件声明原始项目名称和版本。Python MOD 会自动为你完成此操作:
api_version 在每个清单中都是强制性的 —— 缺少该字段的包将被拒绝,而不是静默加载
- 加载器在包启动时打印
<package> v<version> — Powered by Python MOD v<x.y.z> (API <n>)
- 同一字符串也可通过
pythonmod.ATTRIBUTION 获取
gradlew packExamples 会在每个归档文件中写入 ATTRIBUTION.txt
因此,作者只需声明 api_version 即可。
第 3 条 —— 使用本项目源代码需获得项目所有者的授权,且任何此类使用都必须声明原始项目名称、团队和版本。
第 7 条 —— “Python MOD” 作为唯一的项目名称使用;不主张或授权任何翻译名称。
未隶属于 Mojang Studios 或 Microsoft。
Python MOD
Write Minecraft mods in Python.
Python MOD is a Fabric mod that embeds a real Python 3 runtime into Minecraft
and exposes a sandboxed API for registering content, hooking game events and
building screens. Drop a .pymod file into a folder, restart, and your Python
is running inside the game — no Java, no Gradle, no recompiling.
- Minecraft 1.21.1 · Fabric Loader 0.16+ · Fabric API
- Runtime: GraalPy 24.2.2 (CPython 3.11 compatible)
- API level: 1
- Licence: Available License — © 2026 kscm · Project Owner: kscm
Hello, world
hello_world.pymod is a zip with two files:
hello_world.pymod
├── pymod.json
└── src/
└── main.py
pymod.json
{
"id": "hello_world",
"name": "Hello World",
"version": "1.0.0",
"api_version": 1,
"entrypoint": "src/main.py",
"permissions": []
}
src/main.py
import pythonmod
from pythonmod import registry, events
registry.block("hello_block", hardness=1.0, sounds="wood", name="Hello Block")
@events.player_join
def greet(player):
player.send_message("Hello from Python!")
Put it in .minecraft/mods/pythonmods/, start the game, press P.
What the API covers
pythonmod.registry — content
| Function |
Registers |
block(id, hardness, resistance, requires_tool, luminance, sounds, group, item, texture, name) |
A full-cube block, optionally with a block item |
item(id, max_stack, group, texture, name) |
A plain item |
food(id, nutrition, saturation, always_edible, max_stack, group, texture, name) |
An edible item |
Everything is namespaced under your module id, so block("ruby_ore") in a
package with "id": "gems" becomes gems:ruby_ore. Two unrelated packages can
both define ruby_ore and never collide.
Models and English names are generated into a PythonMOD Generated resource
pack, so new content is usable before you have drawn a single texture.
pythonmod.events — game hooks
| Event |
Arguments |
server_tick |
(server) |
server_started / server_stopping |
(server) |
player_join / player_leave |
(player) |
block_break |
(player, pos, block) |
block_use |
(player, pos) |
item_use |
(player) |
client_tick |
(client) |
from pythonmod import events
@events.block_break
def on_break(player, pos, block):
player.send_actionbar("broke %s at %d,%d,%d" % (block.id(), pos.x(), pos.y(), pos.z()))
An unrecognised event name raises at subscription time. A hook that silently
never fires is the most expensive kind of typo, so it is not allowed to happen.
pythonmod.gui — screens
from pythonmod import gui
(gui.screen("Ore Scanner")
.size(280, 160)
.label("Radius", 20, 34)
.slider("blocks", 20, 48, 240, value=16, min=4, max=64, on_change=set_radius)
.checkbox("Include deepslate", 20, 80, checked=True, on_change=set_deepslate)
.button("Scan", 20, 110, 240, 20, on_click=scan)
.open())
Coordinates are relative to the panel and the panel is centred for you.
Light and dark palettes are built in and follow the player's setting — a script
never picks colours by hand.
On a dedicated server there is no client, so open() returns False and logs
a warning instead of raising. Guard with gui.available() when a package is
meant to run on both sides.
pythonmod.xmlgui — declarative HUD (XML)
Declare an in-game HUD panel in gui/*.xml — no Python screen code required.
Each module's gui/ folder is scanned automatically at load time.
gui/hud.xml
<gui>
<screen id="hud_demo" show_page="hud" x="12" y="12">
<label id="title" text="Python MOD · XML HUD" x="0" y="0"
style="color:#1b1f24" style_dark="color:#eceff3"/>
<divider x="0" y="20" w="180"/>
<button id="mine" text="Mine +1" x="0" y="30" w="160" h="20"
style="bg:#1565c0;color:#ffffff" style_dark="bg:#5fa8ff;color:#0b0e12"
click_script="on_click.py" follow_script="after.py"/>
<checkbox id="auto" text="Auto mine" x="0" y="58" checked="true"
style="color:#1b1f24" style_dark="color:#eceff3"
click_script="on_toggle.py"/>
<slider id="speed" text="Speed" x="0" y="84" w="180" value="0.5" min="0" max="1"/>
<text_field id="status" placeholder="Status: ready" x="0" y="110" w="180" h="20"/>
</screen>
</gui>
| Attribute |
On |
Meaning |
style / style_dark |
widget |
CSS-like key:value pairs (color, bg, border). The active light/dark theme picks which one |
click_script |
button, checkbox |
Python file run when the widget is clicked |
follow_script |
button |
Python file run right after click_script completes |
show_page |
screen |
Where to show it: hud (in-game overlay). screen / main_menu are reserved |
x / y |
screen, widget |
Coordinates in GUI pixels; the screen is the panel anchor, a widget is relative to it |
The scripts run in an isolated context — same permissions and sandbox as the
module, but a crash disables only that script, never the whole module. They can
import pythonmod like any other code. A clicked button runs click_script
then follow_script; the same path is reachable from Python:
from pythonmod import xmlgui
xmlgui.trigger("hud_demo", "mine") # runs on_click.py then after.py
See examples/xml_hud_demo/ for a complete, runnable panel (button, checkbox,
slider and text field with light/dark styles and Python scripts).
The manifest
| Field |
Required |
Notes |
id |
yes |
2–64 chars of a-z, 0-9, _. Becomes your registry namespace |
version |
yes |
Free-form |
api_version |
yes |
Must be 1. See Attribution below |
name |
no |
Defaults to id |
description |
no |
Shown in the manager screen |
authors |
no |
Array of strings |
entrypoint |
no |
Defaults to src/main.py |
environment |
no |
*, client or server |
permissions |
no |
See the table below |
Permissions
| Permission |
Risk |
Grants |
file_read |
low |
Reading inside your own data folder |
file_write |
medium |
Writing inside your own data folder |
network |
high |
Outbound sockets |
thread |
high |
Creating threads |
native |
critical |
Native/JNI access — effectively no sandbox |
process |
critical |
Spawning processes — effectively no sandbox |
The sandbox confines file access to pythonmod/data/<your-id>/ regardless of
what is granted. pythonmod.data_path("state.json") builds a legal path;
anything outside that tree is refused before it reaches the filesystem.
Packages asking for native or process produce a loud warning in the log and
a red entry in the manager screen. That is deliberate: those two permissions
hand a script the same power a Java mod has.
In-game manager
Press P (rebindable) for:
- what loaded, what failed, and the exact reason
- what each package registered, and how long it took
- the permissions it was granted, colour-coded by risk
- the last few lines it printed
- a light / dark / auto theme switch, saved to the config
Configuration
.minecraft/config/pythonmod.json
| Key |
Default |
Meaning |
enabled |
true |
Master switch |
autoDownloadRuntime |
true |
Fetch GraalPy on first launch |
mavenRepository |
Maven Central |
Mirror to download from |
verifyChecksums |
true |
Verify every downloaded jar |
theme |
"auto" |
auto, light or dark |
callbackTimeoutMs |
5000 |
A callback exceeding this disables its package |
verboseLogging |
false |
Extra diagnostics |
How it works
preLaunch RuntimeProvisioner downloads GraalPy, verifies SHA-1,
injects it into the Knot class loader
↓
main PythonEngine one shared Engine
SandboxPolicy one Context per package, with its own
permission set and virtual filesystem
PyModLoader scan → validate → unpack → run
PyBridge the single Java object Python can reach
↓
runtime PyEventBridge Fabric callbacks fan out to Python hooks
PyGuiBridge screen descriptions, rendered client-side
XmlHudRenderer XML-declared HUD panels, scanned from gui/*.xml
XmlGuiBridge fires a widget's click/follow scripts
The runtime is not bundled. GraalPy is roughly 200 MB — larger than most
modpacks. It is downloaded once on first launch, checksum-verified, and cached
in .minecraft/pythonmod/runtime/. If the download fails the game still starts;
Python support is simply reported as unavailable.
One context per package, not one shared context. A polyglot context cannot
hold two different permission sets, so a shared one would grant every package
the union of everyone's permissions — one package asking for network would
silently hand network access to all the others. Separate contexts also mean a
crashing package can be disabled on its own.
Guest exceptions never escape. Every call into Python goes through
PythonEngine.invoke, which catches the guest exception, prints the Python
traceback, and disables the offending package. A typo in a script is not
allowed to take the server down.
Building
Requires JDK 21. A local Temurin 21 lives in .tooling/jdk-21; point
org.gradle.java.home in gradle.properties at your own if you prefer.
./gradlew build # builds the mod jar
./gradlew packExamples # packs examples/ into build/pymods/*.pymod
Attribution
Python MOD is distributed under the Available License (see LICENSE),
© 2026 kscm, Project Owner kscm.
Section 6 requires software using this API to state the original project
name and version. Python MOD does that for you:
api_version is mandatory in every manifest — a package without it is
refused rather than silently loaded
- the loader prints
<package> v<version> — Powered by Python MOD v<x.y.z> (API <n>)
when the package starts
- the same string is available as
pythonmod.ATTRIBUTION
gradlew packExamples writes ATTRIBUTION.txt into every archive
Declaring api_version is therefore all an author has to do.
Section 3 — using this project's source code requires authorisation from
the Project Owner, and any such use must state the original project name, team
and version.
Section 7 — "Python MOD" is used as the sole project name; no translated
name is claimed or authorised.
Not affiliated with Mojang Studios or Microsoft.
评论 0
登录后参与评分
还没有评论,来抢沙发吧