File size: 1,905 Bytes
bdda60b
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
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()