You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

求uscxml(状态图)Python绑定代码示例及Python运行SCXML文件方法

Python绑定uscxml的代码示例

前提准备

确保已安装uscxml的Python绑定,可通过以下方式安装(若官方提供pip包):

pip install uscxml

如果是从源码编译,需确保编译时开启了Python绑定的构建选项。

核心代码示例

以下代码实现与uscxml-browser -v <scxml-chart-file>一致的运行逻辑,包含状态流转跟踪:

import uscxml
import time

# 加载目标SCXML文件
scxml_doc = uscxml.Document.from_file("your-scxml-file.scxml")
# 创建状态图解释器实例
interpreter = uscxml.Interpreter(scxml_doc)

# 定义状态变化回调,打印当前激活状态(对应浏览器里的状态流转)
def track_state_changes(event):
    active_states = interpreter.get_active_states()
    print(f"状态流转: {' -> '.join(active_states)}")

# 注册状态变化事件监听
interpreter.add_event_listener(uscxml.EventType.STATE_CHANGE, track_state_changes)

# 启动状态图解释器
interpreter.start()

# 运行事件循环,持续处理状态逻辑
try:
    while interpreter.is_running():
        interpreter.step()  # 处理待执行的状态逻辑与事件
        time.sleep(0.01)    # 降低CPU占用
except KeyboardInterrupt:
    interpreter.stop()
    print("状态图已终止运行")

额外说明

  • 若SCXML中包含需外部触发的事件(如<transition event="user-click" ...>),可通过以下代码发送事件:
    interpreter.enqueue_event(uscxml.Event("user-click"))
    
  • get_active_states()方法会返回当前所有激活的状态列表,和uscxml-browser中显示的状态流转完全对应。

内容的提问来源于stack exchange,提问作者stustd

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.02 23:08:16