mcp / app.py
wcr's picture
Update app.py
663c3e8 verified
import gradio as gr
import sys
import io
import subprocess
# 执行 Python 代码
def run_python_code(code: str) -> str:
stdout = io.StringIO()
stderr = io.StringIO()
sys.stdout = stdout
sys.stderr = stderr
try:
exec(code)
except Exception as e:
return f"Error:\n{str(e)}"
finally:
sys.stdout = sys.__stdout__
sys.stderr = sys.__stderr__
output = stdout.getvalue()
error = stderr.getvalue()
if error:
return f"Error:\n{error}"
else:
return output or "No output."
# 执行 Shell 命令
def run_shell_command(cmd: str) -> str:
try:
result = subprocess.run(
cmd,
shell=True,
stdout=subprocess.PIPE,
stderr=subprocess.PIPE,
text=True
)
if result.returncode != 0:
return f"Error:\n{result.stderr}"
else:
return result.stdout
except subprocess.TimeoutExpired:
return "Error:\n命令执行超时。"
except Exception as e:
return f"Error:\n{str(e)}"
# 统一入口函数
def execute_input(type_choice, input_text):
if type_choice == "Python":
return run_python_code(input_text)
else:
return run_shell_command(input_text)
# Gradio 界面
demo = gr.Interface(
fn=execute_input,
inputs=[
gr.Radio(choices=["Python", "Shell"], label="执行类型", value="Python"),
gr.TextArea(
label="输入 Python 代码或 Shell 命令",
placeholder="例如:print('Hello World') 或 echo 'Hello'"
)
],
outputs=gr.Textbox(label="执行结果", lines=10),
title="代码与命令执行器",
description="选择执行类型并输入对应的代码或命令,查看执行结果。",
theme="default"
)
# 启动服务
if __name__ == "__main__":
demo.launch(mcp_server=True)