I have this code, product of my imagination and ChatGPT help:
import subprocess
import threading
import tkinter as tk
class PingThread(threading.Thread):
def __init__(self, text_widget):
super().__init__()
self.text_widget = text_widget
self.process = None
self.stop_event = threading.Event()
def run(self):
self.process = subprocess.Popen(['cmd'], stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.PIPE, shell=True)
self.process.stdin.write(b'ping -t google.com\n')
self.process.stdin.flush()
while not self.stop_event.is_set():
line = self.process.stdout.readline().decode('cp866')
if not line:
break
self.text_widget.insert(tk.END, line)
self.text_widget.see(tk.END)
def stop(self):
if self.process:
self.process.communicate(b'\x03')
self.process.wait() #Window freezes on the .communicate line, so this and line below are not executing at all
self.stop_event.set()
def ping():
ping_thread = PingThread(text)
ping_thread.start()
def handle_ctrl_c(event):
ping_thread.stop()
text.insert(tk.END, '\nProcess terminated.\n')
root.bind('<Control-c>', handle_ctrl_c)
root = tk.Tk()
text = tk.Text(root)
text.pack()
button = tk.Button(root, text='Ping', command=ping)
button.pack()
root.mainloop()
I'm trying to create a console simulation in Tkinter. I'm sending ping request and listening console for it's response. All works well, except Ctrl+C
command, which should finishes ping
execution and response the statistics from console. Window just freezing, when i try to send self.process.communicate(b'\x03')
What causes that? As i understand, this line should send Ctrl+C
to the console and while loop
should receive last lines from the console, with ping's statistics?