import gradio as gr import subprocess def run_command(command): try: # Run the command and capture the output result = subprocess.run( command, shell=True, capture_output=True, text=True, timeout=60 # Prevent hanging commands ) # Combine stdout and stderr output = result.stdout if result.stderr: output += "\n--- STDERR ---\n" + result.stderr if not output.strip(): return "Command executed successfully with no output." return output except subprocess.TimeoutExpired: return "Error: Command timed out after 60 seconds." except Exception as e: return f"Error executing command: {str(e)}" # Create the Gradio interface with gr.Blocks(title="Hugging Face Container Shell") as demo: gr.Markdown("# Container Shell Access") gr.Markdown("Run terminal commands directly inside the Hugging Face Space container.") with gr.Row(): command_input = gr.Textbox( label="Terminal Command", placeholder="e.g., ls -la, pwd, whoami", lines=1 ) with gr.Row(): run_button = gr.Button("Run Command", variant="primary") with gr.Row(): command_output = gr.Textbox( label="Output", lines=20, interactive=False ) # Bind the button and enter key to the function run_button.click(fn=run_command, inputs=command_input, outputs=command_output) command_input.submit(fn=run_command, inputs=command_input, outputs=command_output) if __name__ == "__main__": demo.launch()