Spaces:
Building
Building
import gradio as gr | |
import subprocess | |
import threading | |
# Shared variable for storing command output | |
output = "" | |
output_lock = threading.Lock() | |
# Function to execute CLI commands in a separate thread | |
def execute_command(cmd): | |
global output | |
try: | |
# Execute command | |
process = subprocess.Popen(cmd, shell=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE) | |
# Capture the output and errors | |
stdout, stderr = process.communicate() | |
# Update the output string safely using a lock | |
with output_lock: | |
if stdout: | |
output += stdout.decode('utf-8') + '\n' | |
if stderr: | |
output += stderr.decode('utf-8') + '\n' | |
except Exception as e: | |
# Handle any exceptions and append to the output | |
with output_lock: | |
output += f"Error: {str(e)}\n" | |
# Function to be called by Gradio to run the command | |
def run_command(cmd): | |
global output | |
# Clear previous output | |
output = "" | |
# Start a new thread to execute the command | |
command_thread = threading.Thread(target=execute_command, args=(cmd,)) | |
command_thread.start() | |
# Return immediately while the thread processes the command | |
return "Running command..." | |
# Function to return the current output | |
def get_output(): | |
global output | |
with output_lock: | |
return output | |
# Gradio interface setup | |
with gr.Blocks() as demo: | |
cmd_input = gr.Textbox(label="Command", placeholder="Type your command here...") | |
cmd_output = gr.Textbox(label="Output", placeholder="Command output will appear here...", lines=10) | |
run_button = gr.Button("Run Command") | |
output_button = gr.Button("Get Output") | |
run_button.click(fn=run_command, inputs=cmd_input, outputs=cmd_output) | |
output_button.click(fn=get_output, inputs=None, outputs=cmd_output) | |
# Launch the Gradio interface | |
demo.launch() |