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

如何在Gradio中实现脚本运行的进度与状态可视化提示?

你之前直接调用text_informs.update()的方式在Gradio里不会生效,因为Gradio的UI更新逻辑是通过函数返回值来驱动的,而非直接操作组件实例。下面给你两种简单有效的实现方式,都能让用户清晰看到脚本的运行状态:

方案1:用Markdown组件实时显示状态

通过生成器函数逐步返回状态内容,让UI实时响应:

import subprocess
import gradio as gr

def generate_output(input_path, output_path):
    # 先返回"运行中"状态
    yield "运行中,请稍候..."
    try:
        # 改用check_call,脚本出错时会抛出异常
        cmd = f'python parse.py "{input_path}" "{output_path}"'
        subprocess.check_call(cmd, shell=True)
        # 执行完成返回成功提示
        yield "✅ 执行完成!"
    except subprocess.CalledProcessError:
        # 出错返回错误提示
        yield "❌ 执行失败,请检查输入路径或脚本!"

with gr.Blocks() as demo:
    tb_input_path = gr.Textbox(label="输入路径")
    tb_output_path = gr.Textbox(label="输出路径")
    # 状态显示组件
    text_informs = gr.Markdown(label="执行状态")
    
    with gr.Row():
        btn_run = gr.Button('RUN', elem_id='generate')
        # 把状态组件设为输出,函数返回值会自动更新它
        btn_run.click(
            fn=generate_output,
            inputs=[tb_input_path, tb_output_path],
            outputs=text_informs
        )

demo.launch()

方案2:禁用按钮+进度条,防止重复操作

在脚本运行时禁用按钮,避免用户重复点击,同时用进度条强化“正在处理”的感知:

import subprocess
import gradio as gr

def generate_output(input_path, output_path, progress=gr.Progress()):
    # 第一步:禁用按钮,返回运行状态
    yield gr.Button.update(interactive=False), "运行中..."
    # 进度条提示(可自定义描述)
    progress(0.3, desc="正在初始化")
    
    try:
        progress(0.7, desc="执行脚本")
        cmd = f'python parse.py "{input_path}" "{output_path}"'
        subprocess.check_call(cmd, shell=True)
        # 完成后恢复按钮可用,返回成功状态
        yield gr.Button.update(interactive=True), "✅ 执行完成!"
    except subprocess.CalledProcessError:
        # 出错后恢复按钮可用,返回错误状态
        yield gr.Button.update(interactive=True), "❌ 执行失败,请检查输入路径或脚本!"

with gr.Blocks() as demo:
    tb_input_path = gr.Textbox(label="输入路径")
    tb_output_path = gr.Textbox(label="输出路径")
    text_informs = gr.Markdown(label="执行状态")
    
    with gr.Row():
        btn_run = gr.Button('RUN', elem_id='generate')
        # 输出包含按钮和状态组件,按顺序返回更新值
        btn_run.click(
            fn=generate_output,
            inputs=[tb_input_path, tb_output_path],
            outputs=[btn_run, text_informs]
        )

demo.launch()

重要提示

  • 必须通过函数返回值(或yield的内容)更新UI,不能直接在函数内调用组件的update方法
  • subprocess.check_call会在脚本执行失败时抛出异常,方便捕获错误;原来的subprocess.call只会返回退出码,不会触发try-except
  • 生成器函数(带yield)是Gradio实现实时状态更新的标准方式,适合处理耗时任务

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.31 03:51:36