Skip to content

Instantly share code, notes, and snippets.

@RhetTbull
Created June 22, 2023 06:08
Show Gist options
  • Save RhetTbull/c61df45c317eb8004adee87334298298 to your computer and use it in GitHub Desktop.
Save RhetTbull/c61df45c317eb8004adee87334298298 to your computer and use it in GitHub Desktop.
Redirect output of a subprocess to a tkinter text box in real-time
"""Redirect output of a command to a tkinter text box in real-time"""
from __future__ import annotations
import subprocess
import threading
import tkinter as tk
def update_text_box(text_box: tk.Text, proc: subprocess.Popen):
"""Create a closure to capture proc and text_box which will be called to update the text box"""
# closure to capture proc and text_box
def _update_text_box():
for line in proc.stdout:
text_box.insert(tk.END, line.decode())
text_box.yview(tk.END)
return _update_text_box
def run_command(command: list[str], text_box: tk.Text):
"""Run a command and redirect output to a text box in real-time"""
proc = subprocess.Popen(
command,
stdout=subprocess.PIPE,
stderr=subprocess.STDOUT,
)
# Start a separate thread to update the text box with output
thread = threading.Thread(target=update_text_box(text_box, proc))
thread.start()
# Create the main Tkinter window
window = tk.Tk()
# Create a text box widget
text_box = tk.Text(window, height=40, width=80)
text_box.pack()
def on_command():
"""Callback for the button widget"""
return run_command(["ls", "-l", ".."], text_box)
# Create a button widget
button = tk.Button(window, text="Run command", command=on_command)
button.pack()
# Start the Tkinter event loop
window.mainloop()
@Yangeok
Copy link

Yangeok commented Dec 28, 2023

Should i currect identation for using your code snippet?

@RhetTbull
Copy link
Author

@Yangeok I'm sorry I don't understand the question. I think you are asking how to do attribution if you use this code? If so just put a note in the README with my name or GitHub ID. The code is under MIT License which means you can freely use it.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment