Python-Compiler / app.py
Omega-02's picture
Update app.py
580fa5d verified
raw
history blame contribute delete
918 Bytes
import gradio as gr
import sys
from io import StringIO
def run_code(code):
try:
# Redirect stdout to a buffer
output_buffer = StringIO()
sys.stdout = output_buffer
# Execute the code in a separate namespace
namespace = {}
exec(code, namespace)
# Get the output from the buffer
output = output_buffer.getvalue()
except Exception as e:
output = f"Error: {str(e)}"
finally:
# Reset stdout to its original value
sys.stdout = sys.__stdout__
return output
# Define the Gradio interface
with gr.Blocks() as demo:
code_input = gr.Textbox(label="Enter Python Code", lines=10)
run_button = gr.Button("Run Code")
output_text = gr.Textbox(label="Output", lines=10)
# Define the event handler
run_button.click(fn=run_code, inputs=code_input, outputs=output_text)
# Launch the Gradio app
demo.launch()