2013-01-16 60 views
1

我工作的一所学校项目,开发蟒蛇平台定制的媒体播放器。问题是当我使用time.sleep(持续时间)时,它会阻止我的GUI的主循环阻止它更新。我咨询了我的主管,被告知使用多线程,但我不知道如何使用线程。有人会告诉我如何在下面的场景中实现线程吗?如何使用wxPython的线程,以防止阻塞主循环


代码:

def load_playlist(self, event): 
    playlist = ["D:\Videos\test1.mp4", "D:\Videos\test2.avi"] 
    for path in playlist: 
     #calculate each media file duration 
     ffmpeg_command = ['C:\\MPlayer-rtm-svn-31170\\ffmpeg.exe', '-i' , path] 

     pipe = subprocess.Popen(ffmpeg_command, shell=True, stdout=subprocess.PIPE, stderr=subprocess.STDOUT) 
     results = pipe.communicate() 

     #Regular expression to get the duration 
     length_regexp = 'Duration: (\d{2}):(\d{2}):(\d{2})\.\d+,' 
     re_length = re.compile(length_regexp) 

     # find the matches using the regexp that to compare with the buffer/string 
     matches = re_length.search(str(results)) 
     #print matches 

     hour = matches.group(1) 
     minute = matches.group(2) 
     second = matches.group(3) 

     #Converting to second 
     hour_to_second = int(hour) * 60 * 60 
     minute_to_second = int(minute) * 60 
     second_to_second = int(second) 

     num_second = hour_to_second + minute_to_second + second_to_second 
     print num_second 

     #Play the media file 
     trackPath = '"%s"' % path.replace("\\", "/") 
     self.mplayer.Loadfile(trackPath) 

     #Sleep for the duration of second(s) for the video before jumping to another video 
     time.sleep(num_second) #THIS IS THE PROBLEM# 
+0

难道迈克的或我的回答解决问题了吗?如果是这样,请接受/ upvote以表示您对我们时间的赞赏。 – bouke

回答

3

你将开始一个新的线程,就像任何其他的多线程例子:

from threading import Thread 

# in caller code, start a new thread 
Thread(target=load_playlist).start() 

然而,你必须确保调用宽x必须处理线程间通信。你不能从这个新线程调用wx-code。它会段错误。因此,使用wx.CallAfter

# in load_playlist, you have to synchronize your wx calls 
wx.CallAfter(self.mplayer.Loadfile, trackPath) 
6

你可能会想看看在wxPython的维基其中有使用线程,队列和其他有趣的事情的几个例子:

我也写了关于这个问题的教程在这里:http://www.blog.pythonlibrary.org/2010/05/22/wxpython-and-threads/

要记住的主要是当你使用线程时,你不能直接调用你的wx方法。 myWidget.SetValue等)。相反,你需要使用的wxPython的线程安全的方法之一:wx.CallAfter,wx.CallLater或wx.PostEvent