Spaces:
Running
Running
Download app.py from vmohan-sn/PythonCodeExec: direct link, hf CLI and curl.
- Browser
- Download file 945 Bytes
-
https://huggingface.co/spaces/vmohan-sn/PythonCodeExec/resolve/main/app.py
- Command line
-
hf download hf://spaces/vmohan-sn/PythonCodeExec/app.py
-
curl -L -o app.py https://huggingface.co/spaces/vmohan-sn/PythonCodeExec/resolve/main/app.py
945 Bytes
| import gradio as gr | |
| from io import StringIO | |
| import sys | |
| def execute_code(code: str) -> str: | |
| """ | |
| Execute Python code and return the output or error message. | |
| Args: | |
| code (str): The Python code to execute. | |
| Returns: | |
| str: The output of the executed code or the error message if an exception occurs. | |
| """ | |
| old_stdout = sys.stdout | |
| redirected_output = sys.stdout = StringIO() | |
| try: | |
| exec(code) | |
| return redirected_output.getvalue() | |
| except Exception as e: | |
| return str(e) | |
| finally: | |
| sys.stdout = old_stdout | |
| # Create the Gradio interface | |
| demo = gr.Interface( | |
| fn=execute_code, | |
| inputs=gr.Code(label="Python Code", language="python"), | |
| outputs=gr.Textbox(label="Output"), | |
| title="Python Code Executor", | |
| description="Execute Python code and see the output. This app is also an MCP server for LLMs." | |
| ) | |
| if __name__ == "__main__": | |
| demo.launch(mcp_server=True) |