-
-
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/env 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 | |
import sys | |
from subprocess import Popen, PIPE, STDOUT | |
from textwrap import dedent | |
from threading import Thread | |
try: | |
import Tkinter as tk | |
except ImportError: | |
import tkinter as tk # Python 3 | |
info = print | |
class StopProcessDemo: | |
def __init__(self, root): | |
self.root = root | |
# show subprocess' stdout in GUI | |
self._var = tk.StringVar() # put subprocess output here | |
tk.Label(root, textvariable=self._var).pack() | |
# to access event's .data use tcl to bind the event | |
# https://stackoverflow.com/questions/41912004/how-to-use-tcl-tk-bind-function-on-tkinters-widgets-in-python | |
on_reading_line = root.register(self._var.set) | |
root.tk.call("bind", root, '<<line>>', on_reading_line + " %d") | |
# stop subprocess using a button | |
tk.Button(root, text="Stop subprocess", command=self.stop).pack() | |
for t in range(1): | |
# start dummy subprocess to generate some output | |
self.process = Popen([sys.executable, "-u", "-c", dedent(""" | |
import itertools, sys, time | |
for i in itertools.count(): | |
print(i, sys.argv[1]) | |
time.sleep(0.1) | |
"""), str(t)], stdout=PIPE, stderr=STDOUT, universal_newlines=True) | |
# launch thread to read the subprocess output: | |
# process.readline -> event <<line>> -> label | |
t = Thread(target=self.reader_thread, | |
# https://mail.python.org/pipermail/tkinter-discuss/2013-November/003526.html | |
args=[lambda line: root.event_generate('<<line>>', when='tail', data=line)]) | |
t.daemon = True # close pipe if GUI process exits | |
t.start() | |
def reader_thread(self, emit): | |
"""Read subprocess output and emit lines.""" | |
with self.process.stdout as pipe: | |
for line in iter(pipe.readline, ''): | |
emit(line) | |
def stop(self): | |
"""Stop subprocess and quit GUI.""" | |
info('stoping') | |
self.process.terminate() # tell the subprocess to exit | |
# kill subprocess if it hasn't exited after a countdown | |
def kill_after(countdown): | |
if self.process.poll() is None: # subprocess hasn't exited yet | |
countdown -= 1 | |
if countdown < 0: # do kill | |
info('killing') | |
self.process.kill() # more likely to kill on *nix | |
else: | |
self.root.after(100, kill_after, countdown) | |
return # continue countdown | |
# clean up | |
self.process.stdout.close() # close fd | |
self.process.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()