How come this way of ending a thread is not working? - python

I just came out with my noob way of ending a thread, but I don't know why it's not working. Would somebody please help me out?
Here's my sample code:
import wx
import thread
import time
import threading
class TestFrame(wx.Frame):
def __init__(self):
wx.Frame.__init__(self, parent = None, id = -1, title = "Testing", pos=(350, 110), size=(490, 200), style=wx.SYSTEM_MENU | wx.CAPTION | wx.CLOSE_BOX | wx.MINIMIZE_BOX)
self.panel = wx.Panel(self)
self.stop = False
self.StartButton = wx.Button(parent = self.panel, id = -1, label = "Start", pos = (110, 17), size = (50, 20))
self.MultiLine = wx.TextCtrl(parent = self.panel, id = -1, pos = (38, 70), size = (410, 90), style = wx.TE_MULTILINE|wx.TE_READONLY|wx.TE_AUTO_URL)
self.Bind(wx.EVT_BUTTON, self.OnStart, self.StartButton)
self.Bind(wx.EVT_CLOSE, self.OnClose)
def OnStart(self, event):
self.StartButton.Disable()
self.NewThread = threading.Thread(target = self.LongRunning)
self.NewThread.start()
def OnClose(self, event):
self.stop = True
BusyBox = wx.BusyInfo("Just a moment please!", self)
wx.Yield()
while True:
try:
if not self.NewThread.isAlive():
self.Destroy()
break
time.sleep(0.5)
except:
self.Destroy()
break
def LongRunning(self):
Counter = 1
while True:
time.sleep(2)
print "Hello, ", Counter
self.MultiLine.AppendText("hello, " + str(Counter) + "\n") #If you comment out this line, everything works fine. Why can't I update the fame after I hit the close button?
Counter = Counter + 1
if self.stop:
break
class TestApp(wx.App):
def OnInit(self):
self.TestFrame = TestFrame()
self.TestFrame.Show()
self.SetTopWindow(self.TestFrame)
return True
def main():
App = TestApp(redirect = False)
App.MainLoop()
if __name__ == "__main__":
main()
As you can see in my code, there's a infinite loop in the thread, what I tell the thread to do is break out of the loop once I click the close button. But the problem is, every time when I hit the close button, it seems the code stuck at self.MultiLine.AppendText("hello, " + str(Counter) + "\n") line, I don't know why. Anybody can help?

Try using a thread safe method such as wx.CallAfter when updating your multiline.
def LongRunning(self):
Counter = 1
while True:
time.sleep(2)
print "Hello, ", Counter
wx.CallAfter(self.updateMultiLine, "hello, " + str(Counter) + "\n")
Counter = Counter + 1
if self.stop:
break
def updateMultiLine(self, data):
self.MultiLine.AppendText(data)

In general with GUI toolkits, only one thread should access GUI functions. An exception is wx.CallAfter
As you (should) know, software defects can be classified into three groups:
Your bugs.
Their bugs.
Threads.
;)

Related

moviepy progress bar in wxPython statusbar

Running on Python 3.x on Windows 10
I'm working on a script to help automate compiling a .tiff image sequence into a video. I'm using wxPython to build the GUI. First I create the window class and set a global variable for the window.
global main_window
main_window = self
Then I have a function I use to write to the statusbar and also print the values to console(occasionally I also add code to write a log file from the text I send to this function).
def update_status_bar(window, text):
status = str(text)
window.statusbar.SetStatusText(status)
print(status)
window.Refresh()
window.Update()
wx.SafeYield(win=None, onlyIfNeeded=False)
This is the moviePy function I wrote to convert the image sequence into ta video.
def video_from_sequence(image_sequence, video, fps):
img = []
update_status_bar(main_window, 'Getting Image Directory')
path = os.path.dirname(os.path.realpath(image_sequence))
print(path)
update_status_bar(main_window, 'Getting List of Image Files')
for root, dirs, files in os.walk(path):
for file in files:
if file.endswith('.tiff'):
img.append(file)
os.chdir(path)
update_status_bar(main_window, 'Creating Video From Image Sequence')
clip = ImageSequenceClip(img, fps=fps)
update_status_bar(main_window, clip.write_videofile(video, fps=fps))
The print to console does show the progress, however the statusbar is not populating with the current progress of the process. Because I'd like to eventually have this run as a .pyw, where the statusbar shows the progress, it's important to me that I have the progressbar show up in the statusbar, however I'm having trouble finding out a way to do this.
UPDATE (06/01/2020):
I've managed to use 2 functions to start and stop the progress bar, and created the status bar with 2 panels instead of one.
My code within the MainWindow class for the status bar has been changed to:
self.statusbar = self.CreateStatusBar(2)
self.progress_bar = wx.Gauge(self.statusbar, -1, size=(280,25), style=wx.GA_PROGRESS)
self.progress_bar_active = False
self.Show()
self.progress_bar.SetRange(50)
self.progress_bar.SetValue(0)
My function to start the animation:
def start_busy_statusbar(window):
window.count = 0
window.proc = subprocess.Popen(['ping', '127.0.0.1', '-i', '0.2'], stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
while True:
wx.Yield()
try:
list_data = window.proc.stdout.readline()
wx.Yield()
except:
break
if len(list_data) == 0:
break
window.progress_bar.Pulse()
wx.Yield()
window.count += 1
And my function to stop the animation:
def stop_busy_statusbar(window):
window.progress_bar.Destroy()
window.progress_bar = wx.Gauge(window.statusbar, -1, size=(280, 25), style=wx.GA_PROGRESS)
Which does feel a bit crude, but it works.
So my convert() function that calls the video_from_sequence() function looks like this:
def convert(self, event):
start_busy_statusbar(main_window)
image_sequence = str(self.text_image_sequence_dir.GetValue())
original_video = str(self.text_original_video_dir.GetValue())
if image_sequence.endswith('.tiff') and original_video.endswith('.mkv'):
try:
new_video = str(original_video)[:-4] + '_1080p.mkv'
temp_video = str(original_video)[:-4] + '_temp.mkv'
print(image_sequence)
print(original_video)
print(new_video)
fps = get_frame_rate(original_video)
print(fps)
video_from_sequence(image_sequence, temp_video, fps)
except FileNotFoundError as e:
e = str(e).replace('Errno 2] ', '')
e = e.replace('directory:', 'directory:\n')
warning(e)
update_status_bar(self, 'Finished')
else:
warning('You must enter valid paths for both a tiff sequence and original video.')
stop_busy_statusbar(main_window)
What I'm running into now, is that the Window locks up while it's processing the image sequence. It's been suggested that I use a seperate thread or utilize the wx.Yield. I'm not quite sure how to execute these things. I've tried CallAfter(function(vars)) but that doesn't seem to work.
I've copied code snippets demonstrating how this works in wxPython, but I don't really understand how it works, and can't get it to work in my script.
Here is a very old example of implementing a progress bar in the statusbar.
It should give you enough to work with.
import wx
import subprocess
class MainFrame(wx.Frame):
def __init__(self):
wx.Frame.__init__(self, None, title='Statusbar progress')
panel = wx.Panel(self)
self.start_btn = wx.Button(panel, label='Start')
self.start_btn.Bind(wx.EVT_BUTTON, self.OnStart)
self.stop_btn = wx.Button(panel, label='Stop')
self.stop_btn.Bind(wx.EVT_BUTTON, self.OnStop)
self.Bind(wx.EVT_CLOSE, self.OnExit)
self.text = wx.TextCtrl(panel, -1, 'Type text here')
btn_sizer = wx.BoxSizer(wx.HORIZONTAL)
btn_sizer.Add(self.start_btn)
btn_sizer.Add(self.stop_btn)
btn_sizer.Add(self.text)
panel.SetSizer(btn_sizer)
self.statusbar = self.CreateStatusBar(3)
self.text1 = wx.StaticText(self.statusbar,-1,("Static text"))
self.text2 = wx.StaticText(self.statusbar,-1,("Count Text"))
self.progress_bar = wx.Gauge(self.statusbar, -1, style=wx.GA_HORIZONTAL|wx.GA_SMOOTH)
sizer = wx.BoxSizer(wx.HORIZONTAL)
sizer.Add(self.text1, 0, wx.ALL, 5)
sizer.Add(self.text2, 1, wx.ALL, 5)
sizer.Add(self.progress_bar, 2, wx.ALL, 5)
self.statusbar.SetSizer(sizer)
self.Show()
self.progress_bar.SetRange(50)
self.progress_bar.SetValue(0)
def OnStart(self,event):
self.start_btn.Enable(False)
self.text1.SetLabelText("Started")
self.count = 0
self.proc = subprocess.Popen(['ping','127.0.0.1','-i','0.2'],stdin=subprocess.PIPE, stdout=subprocess.PIPE,stderr=subprocess.PIPE)
while True:
try:
list_data = self.proc.stdout.readline()
except:
break
if len(list_data) == 0:
break
self.progress_bar.Pulse()
self.count+=1
self.text2.SetLabelText("Count "+str(self.count))
wx.GetApp().Yield()
def OnStop(self,event):
self.start_btn.Enable(True)
self.text1.SetLabelText("Stopped")
try:
self.proc.kill()
except:
pass
def OnExit(self,event):
try:
self.proc.kill()
except:
pass
self.Destroy()
if __name__ == '__main__':
app = wx.App()
frame = MainFrame()
app.MainLoop()

Python PYserial WxPython Threading

Can any one please tell me whats wrong with this piece of code.
When I press button 1 - everything is good. I want to press button2 - to stop the process started by button 1 and do an another process. I am unable to do it - MY GUI is going irresponsive.
You are welcome to edit the serial communication with PRINT statements if you like in doit and doit2 functions.
Please dont comment about how I made the GUI - it is just a quick example. Please comment on why I am unable to pass the pill2kill - when I press the button 2. And why my GUI is going to irresponsive state.
import threading
import time
import numpy as np
import serial
from Transmit import Write
from Receive import Read
import struct
import time
import serial.tools.list_ports
import wx
class windowClass(wx.Frame):
def __init__(self, parent, title):
appSize_x = 1100
appSize_y = 800
super(windowClass, self).__init__(parent, title = title, style = wx.MINIMIZE_BOX | wx.SYSTEM_MENU | wx.CLOSE_BOX |wx.CAPTION, size = (appSize_x, appSize_y))
self.basicGUI()
self.Centre()
self.Show()
def basicGUI(self):
# Main Panel
panel1 = wx.Panel(self)
panel1.SetBackgroundColour('#D3D3D3')
firmware_version = wx.StaticText(panel1, -1, "RANDOM1", pos = (70, 10) )
firmware_version_text_control = wx.TextCtrl(panel1, -1, size = (70,25), pos = (105,40))
pump_model_serial_number = wx.StaticText(panel1, -1, "RANDOM2", pos=(25, 75))
pump_model_serial_number.SetBackgroundColour('yellow')
model = wx.StaticText(panel1, -1, "RANDOM3", pos=(110, 100))
self.listbox = wx.ListBox(panel1, -1, size = (300,250), pos = (20,135))
clear_history = wx.Button(panel1, -1, 'BUTTON1', size = (225,30), pos = (40, 400))
clear_history.SetBackgroundColour('RED')
clear_history.Bind(wx.EVT_BUTTON, self.OnClearHistory)
clear_history2 = wx.Button(panel1, -1, 'BUTTON2', size=(225, 30), pos=(40, 500))
clear_history2.SetBackgroundColour('GREEN')
clear_history2.Bind(wx.EVT_BUTTON, self.OnClearHistory2)
def OnClearHistory(self, event):
self.pill2kill = threading.Event()
self.t = threading.Thread(target=self.doit, args=(self.pill2kill, "task"))
self.t.start()
self.t.join()
def OnClearHistory2(self, event):
self.pill2kill.set()
self.t1 = threading.Thread(target=self.doit2)
self.t1.start()
time.sleep(5)
self.t1.join()
def doit(self, stop_event, arg):
while not stop_event.wait(1):
print ("working on %s" % arg)
ser = serial.Serial(3, 115200)
c = ser.write('\x5A\x03\x02\x02\x02\x09')
print c
d = ser.read(7)
print d.encode('hex')
ser.close()
print("Stopping as you wish.")
def doit2(self):
#print ("working on %s" % arg)
ser = serial.Serial(3, 115200)
c = ser.write('\x5A\x03\x02\x08\x02\x0F') # Writing to an MCU
print c
d = ser.read(7)
print d.encode('hex')
ser.close()
def random():
app = wx.App()
windowClass(None, title='random')
app.MainLoop()
random()
Don't use the .join commands. They are blocking the main thread.
See this SO question for an in depth description:
what is the use of join() in python threading
Thread.join will block until the thread terminates. If your GUI's event handlers are blocked and unable to return to the MainLoop then other events can not be received and dispatched, and so the application appears to be frozen.

Python thread runs even after closing WxPython application

the following code takes screenshots and logs keystrokes and mouse movements. It uses wxpython as GUI framework. I'm using python threads for screenshot and logging service. But whenever I close the GUI application. Threads are still running. How to stop those threads after closing the application?
import wx
import threading
import sys
import subprocess
import time
from pymouse import PyMouse
from pymouse import PyMouseEvent
from pykeyboard import PyKeyboard
from pykeyboard import PyKeyboardEvent
import pyscreenshot as ImageGrab
from PIL import Image
from PIL import ImageFont
from PIL import ImageDraw
import gtk.gdk
import urllib2, urllib
import Cookie
MouseMovesCount = 0
MouseClicksCount = 0
KeyStrokesCount = 0
class OD_App(wx.App):
def OnInit(self):
frame = OD_MainFrame ("Login", (0, 0), (350, 200))
self.SetTopWindow(frame)
loginPanel = OD_LoginPanel (frame)
self.Bind(wx.EVT_CLOSE, self.OnCloseWindow)
frame.Show()
return True
def OnCloseWindow (self, event):
self.Destroy()
class OD_MainFrame(wx.Frame):
def __init__(self, title, pos, size):
wx.Frame.__init__(self, None, -1, title, pos, size)
self.CreateStatusBar()
class OD_LoginPanel(wx.Panel):
def __init__(self, frame):
self.panel = wx.Panel(frame)
self.frame = frame
self.frame.SetStatusText("Authentication required!")
self.showLoginBox()
def showLoginBox (self):
# Create the sizer
sizer = wx.FlexGridSizer(rows=3, cols=2, hgap=5, vgap=15)
# Username
self.txt_Username = wx.TextCtrl(self.panel, 1, size=(150, -1))
lbl_Username = wx.StaticText(self.panel, -1, "Username:")
sizer.Add(lbl_Username,0, wx.LEFT|wx.TOP| wx.RIGHT, 50)
sizer.Add(self.txt_Username,0, wx.TOP| wx.RIGHT, 50)
# Password
self.txt_Password = wx.TextCtrl(self.panel, 1, size=(150, -1), style=wx.TE_PASSWORD)
lbl_Password = wx.StaticText(self.panel, -1, "Password:")
sizer.Add(lbl_Password,0, wx.LEFT|wx.RIGHT, 50)
sizer.Add(self.txt_Password,0, wx.RIGHT, 50)
# Submit button
btn_Process = wx.Button(self.panel, -1, "&Login")
self.panel.Bind(wx.EVT_BUTTON, self.OnSubmit, btn_Process)
sizer.Add(btn_Process,0, wx.LEFT, 50)
self.panel.SetSizer(sizer)
def OnSubmit(self, event):
username = self.txt_Username.GetValue()
password = self.txt_Password.GetValue()
mydata = [('username',username),('password',password)]
mydata = urllib.urlencode(mydata)
path = 'http://xyz/logincheck.php' #temporary db for testing
req = urllib2.Request(path, mydata)
req.add_header("Content-type", "application/x-www-form-urlencoded")
page = urllib2.urlopen(req).read()
if page == "true":
self.frame.SetStatusText("Authentication Success!")
self.show_other(username)
else:
self.frame.SetStatusText("Authentication Failed!")
def OnCloseWindow (self, event):
self.Destroy()
def show_other(self,username):
self.frame.Destroy()
userpanel = OD_UserPanel()
return True
class OD_UserPanel(wx.App):
def OnInit(self):
userpanel = wx.Frame(None,-1)
self.Bind(wx.EVT_CLOSE, self.OnCloseWindow)
#user_greeting = 'Welcome ' + username + '!'
#username = wx.StaticText(userpanel, -1, user_greeting , style=wx.ALIGN_CENTRE)
userpanel.Show()
mouse_eventer = mouse_event()
mouse_eventer.start()
keyboard_eventer = key_event()
keyboard_eventer.start()
screenshot_eventer = screenshot_thread()
screenshot_eventer.start()
return True
def OnCloseWindow (self, event):
quit()
event.Skip()
raise SystemExit
class mouse_event(PyMouseEvent):
def move(self, x, y):
global MouseMovesCount
MouseMovesCount = MouseMovesCount + 1
print MouseMovesCount
def click(self, x, y, button, press):
global MouseClicksCount
if press:
MouseClicksCount = MouseClicksCount + 1
print MouseClicksCount
else:
MouseClicksCount = MouseClicksCount + 1
print MouseClicksCount
class key_event(PyKeyboardEvent):
global screenshot_eventer
def key_press(self, key):
global KeyStrokesCount
KeyStrokesCount = KeyStrokesCount + 1
print KeyStrokesCount
def key_release(self, key):
global KeyStrokesCount
KeyStrokesCount = KeyStrokesCount + 1
print KeyStrokesCount
class screenshot_thread(threading.Thread):
def __init__(self):
super(screenshot_thread, self).__init__()
self.state = True
# Attributes
def run(self):
self.take_shot()
def stop(self):
self.state = False
threading.Thread._Thread__stop()
def take_shot(self):
while self.state==True:
time.sleep(10)
subprocess.call(['scrot'])
if __name__ == '__main__':
app = OD_App()
app.MainLoop()
Don't call threading.Thread._Thread__stop! The leading underscore is a sign that this is internal api, it's not guaranteed to even exist (in fact, in python3 it's gone).
If you wish the thead to be destroyed automatically, set it to be daemonic:
def __init__(self):
super(screenshot_thread, self).__init__()
self.daemon = True
That will cause it to be automatically destroyed when the last non-daemonic thread has stopped. Or, in your case, just setting the state to False should make the thread exit after 10 seconds.
You defined a stop method in your screenshot_thread class but you does not use it. Calling it in the method OnCloseWindow should do the job.

How do I make wx.TextCtrl multi-line text update smoothly?

I'm working on an GUI program, and I use AppendText to update status in a multi-line text box(made of wx.TextCtrl). I noticed each time there's a new line written in this box, instead of smoothly adding this line to the end, the whole texts in the box just disappear(not in real, just visually) and I have to click the scroll button to check the newly updated/written status line. Why this happening? Should I add some styles? Hopefully you guys can help me out.
Here's my sample code:
import wx
import thread
import time
class TestFrame(wx.Frame):
def __init__(self):
wx.Frame.__init__(self, parent = None, id = -1, title = "Testing", pos=(350, 110), size=(490,530), style=wx.SYSTEM_MENU | wx.CAPTION | wx.CLOSE_BOX | wx.MINIMIZE_BOX)
panel = wx.Panel(self)
self.StartButton = wx.Button(parent = panel, id = -1, label = "Start", pos = (110, 17), size = (50, 20))
self.MultiLine = wx.TextCtrl(parent = panel, id = -1, pos = (38, 70), size = (410, 90), style = wx.TE_MULTILINE|wx.TE_READONLY|wx.TE_AUTO_URL)
self.Bind(wx.EVT_BUTTON, self.OnStart, self.StartButton)
def OnStart(self, event):
self.StartButton.Disable()
thread.start_new_thread(self.LongRunning, ())
def LongRunning(self):
Counter = 1
while True:
self.MultiLine.AppendText("Hi," + str(Counter) + "\n")
Counter = Counter + 1
time.sleep(2)
class TestApp(wx.App):
def OnInit(self):
self.TestFrame = TestFrame()
self.TestFrame.Show()
self.SetTopWindow(self.TestFrame)
return True
def main():
App = TestApp(redirect = False)
App.MainLoop()
if __name__ == "__main__":
main()
try this:
self.logs = wx.TextCtrl(self, id=-1, value='', pos=wx.DefaultPosition,
size=(-1,300),
style= wx.TE_MULTILINE | wx.SUNKEN_BORDER)
self.logs.AppendText(text + "\n")
Try calling the Refresh() method on the textCtrl
Update:
A question has already been asked regarding this problem, here is the answer which pretty much solves it, -its not perfect but maybe you can improve on it...
Here is a thread from the wxpython mailing list regarding the problem which may also be of interest to you.

Python Threading, loading one thread after another

I'm working on a media player and am able to load in a single .wav and play it. As seen in the code below.
foo = wx.FileDialog(self, message="Open a .wav file...", defaultDir=os.getcwd(), defaultFile="", style=wx.FD_MULTIPLE)
foo.ShowModal()
queue = foo.GetPaths()
self.playing_thread = threading.Thread(target=self.playFile, args=(queue[0], 'msg'))
self.playing_thread.start()
But the problem is, when I try to make the above code into a loop for multiple .wav files. Such that while playing_thread.isActive == True, create and .start() the thread. Then if .isActive == False, pop queue[0] and load the next .wav file. Problem is, my UI will lock up and I'll have to terminate the program. Any ideas would be appreciated.
Since is using wx.python, use a Delayedresult, look at wx demos for a complete example.
Full minimal example:
import wx
import wx.lib.delayedresult as inbg
import time
class Player(wx.Frame):
def __init__(self):
self.titulo = "Music Player"
wx.Frame.__init__(self, None, -1, self.titulo,)
self.jobID = 0
self.Vb = wx.BoxSizer(wx.VERTICAL)
self.panel = wx.Panel(self,-1)
self.playlist = ['one','two']
self.abortEvent = inbg.AbortEvent()
self.msg = wx.StaticText(self.panel, -1, "...",pos=(30,-1))
self.msg.SetFont(wx.Font(9, wx.SWISS, wx.NORMAL, wx.BOLD))
self.action = wx.Button(self.panel, -1,"Play Playlist")
self.Bind(wx.EVT_BUTTON, self.StartPlaying,self.action)
self.Vb.Add(self.msg, 0, wx.EXPAND|wx.ALL, 3)
self.Vb.Add(self.action, 0, wx.EXPAND|wx.ALL, 3)
self.panel.SetSizer(self.Vb)
self.Show()
def StartPlaying(self,evt):
self.BgProcess(self.Playme)
def Playme(self,jobID, abortEvent):
print "in bg"
list = self.getPlayList()
print list
for music in list:
self.msg.SetLabel('Playing: %s' % music)
stop = 100
while stop > 0:
print stop
stop -=1
self.msg.SetLabel('Playing: %s [%s ]' % (music,stop))
def _resultConsumer(self, inbg):
jobID = inbg.getJobID()
try:
result = inbg.get()
return result
except Exception, exc:
return False
def getPlayList(self):
return self.playlist
def setPlayList(self,music):
self.playlist.appdend(music)
def BgProcess(self,executar):
self.abortEvent.clear()
self.jobID += 1
inbg.startWorker(self._resultConsumer, executar, wargs=(self.jobID,self.abortEvent), jobID=self.jobID)
app = wx.App(False)
demo = Player()
app.MainLoop()

Categories