-
-
Save zed/42324397516310c86288 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/usr/bin/python | |
""" | |
- read output from a subprocess in a background thread | |
- show the output in the GUI | |
- stop subprocess using a Tkinter button | |
https://stackoverflow.com/questions/15362372/display-realtime-output-of-a-subprocess-in-a-tkinter-widget | |
""" | |
from __future__ import print_function | |
from collections import deque | |
from itertools import islice | |
from subprocess import Popen, PIPE, STDOUT | |
from threading import Thread | |
try: | |
import Tkinter as tk | |
except ImportError: | |
import tkinter as tk # Python 3 | |
try: | |
from Queue import Queue, Empty | |
except ImportError: | |
from queue import Queue, Empty # Python 3 | |
info = print | |
def iter_except(function, exception): | |
"""Works like builtin 2-argument `iter()`, but stops on `exception`.""" | |
try: | |
while True: | |
yield function() | |
except exception: | |
return | |
class StopProcessDemo: | |
def __init__(self, root): | |
self.root = root | |
# start dummy subprocess to generate some output | |
self.proc = Popen(["python", "-u", "-c", """ | |
import itertools, sys, time | |
for i in itertools.count(): | |
print(i) | |
time.sleep(0.5) | |
"""], stdout=PIPE, stderr=STDOUT) | |
# launch thread to read the subprocess output | |
# (put the subprocess output into the queue in a background thread, | |
# get output from the queue in the GUI thread. | |
# Output chain: proc.readline -> queue -> stringvar -> label) | |
q = Queue() | |
t = Thread(target=self.reader_thread, args=[q]).start() | |
# show subprocess' stdout in GUI | |
self._var = tk.StringVar() # put subprocess output here | |
tk.Label(root, textvariable=self._var).pack() | |
self.update(q) # start update loop | |
# stop subprocess using a button | |
tk.Button(root, text="Stop subprocess", command=self.stop).pack() | |
def reader_thread(self, q): | |
"""Read subprocess output and put it into the queue.""" | |
for line in iter(self.proc.stdout.readline, b''): | |
q.put(line) | |
info('done reading') | |
def update(self, q): | |
"""Update GUI with items from the queue.""" | |
# read no more than 10000 lines, use deque to discard lines except the last one, | |
for line in deque(islice(iter_except(q.get_nowait, Empty), 10000), maxlen=1): | |
if line is None: | |
return # stop updating | |
else: | |
self._var.set(line) # update GUI | |
self.root.after(40, self.update, q) # schedule next update | |
def stop(self): | |
"""Stop subprocess and quit GUI.""" | |
info('stoping') | |
self.proc.terminate() # tell the subprocess to exit | |
# kill subprocess if it hasn't exited after a countdown | |
def kill_after(countdown): | |
if self.proc.poll() is None: # subprocess hasn't exited yet | |
countdown -= 1 | |
if countdown < 0: # do kill | |
info('killing') | |
self.proc.kill() # more likely to kill on *nix | |
else: | |
self.root.after(1000, kill_after, countdown) | |
return # continue countdown in a second | |
# clean up | |
self.proc.stdout.close() # close fd | |
self.proc.wait() # wait for the subprocess' exit | |
self.root.destroy() # exit GUI | |
kill_after(countdown=5) | |
root = tk.Tk() | |
app = StopProcessDemo(root) | |
root.protocol("WM_DELETE_WINDOW", app.stop) # exit subprocess if GUI is closed | |
root.mainloop() | |
info('exited') |
@Golflengte: the code is unreadable (formatting). You could post a link where the code is properly formatted instead.
God bless you! I'm working on my first python project with a limited coding background. After weeks of researching the possible methods to stream live data to my graph while keeping it interactive, I think this is the winner.
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Finally some good example.
To use it in windows 8 and Linux I made some modifications. Some buttons to start some subprocesses
Using dir in windows and ls in Linux, Get_iplayer to download some BBC programs.
Still working on improvements, but as being just a Python beginner, like to know if I can still improve my code.
Here my code :
!/usr/bin/python3.4.2
-- coding:utf-8 --
programname = 'tktq02WL.py' test Windows
date 02012015
https://gist.githubusercontent.com/zed/42324397516310c86288/raw/8e156ef9d84f5be258fe96696a24b7d2c5ba22b9/kill-process.py
"""
make a "get_iplayer" file (execution of get_iplayer)
install these files in the Python directory
"""
from future import print_function
from collections import deque
from itertools import islice
from subprocess import Popen, PIPE, STDOUT
from threading import Thread
import subprocess
import sys
import time
from time import ctime
import itertools
try:
import Tkinter as tk
except ImportError:
import tkinter as tk # Python 3
try:
from Queue import Queue, Empty
except ImportError:
from queue import Queue, Empty # Python 3
try:
from tkinter import *
except:
from Tkinter import *
import tkinter as tk
programname = 'tkq02WL.py'
dirtext = ""
dirtextl = "ls -ial"
dirtextw = "dir"
dircmd = ""
recordir = ""
recordirw = 'D:/Video-lib/'
recordirl = "/home/bob/Video"
info = print
print ("Make choice for a process by pressing a button")
def iter_except(function, exception):
"""Works like builtin 2-argument
iter()
, but stops onexception
."""try:
while True:
yield function()
except exception:
return
class Application(tk.Frame):
def init(self, master=None):
Frame.init(self, master)
self.createWidgets()
class Application():
def init(self,root):
self.root = root
self.createWidgets()
#self.root.after(60,self.displaytime)
self.displaytime()
if sys.platform == "linux":
self.recordir =recordirl
self.dircmd = "ls -ial"
self.getiplayercmd = "get_iplayer"
else:
self.recordir = recordirw
self.dircmd = "dir.cmd"
self.getiplayercmd = "get_iplayer.cmd"
#print (self.dircmd)
#print (self.recordir)
Frame.init(self, master)
self.createWidgets()
class StopProcessDemo:
def init(self, root):
self.root = root
self.proc = Popen(["python", "-u", "-c", """
import itertools, sys, time
for i in itertools.count():
print(i)
time.sleep(0.001)
"""], stdout=PIPE, stderr=STDOUT)
start a subproces by choosing a button...
for line in deque(islice(iter_except(q.get_nowait, Empty), 10000), maxlen=1):
if line is None:
return # stop updating
else:
self._var.set(line) # update GUI
print added
def main():
root = Tk()
app=Application(root)
app.root.title(programname)
root.protocol("WM_DELETE_WINDOW", app.stop) # exit subprocess if GUI is closed
root.mainloop()
info('exited')
if name == 'main':
main()