【问题标题】:how to use wxpython threading to prevent blocking main loop如何使用 wxpython 线程来防止阻塞主循环
【发布时间】:2012-12-30 11:25:58
【问题描述】:

我正在做一个学校项目,在 python 平台上开发一个定制的媒体播放器。问题是当我使用 time.sleep(duration) 时,它会阻止我的 GUI 的主循环,从而阻止它更新。我咨询了我的主管,并被告知要使用多线程,但我不知道如何使用线程。有人会建议我如何在下面的场景中实现线程吗?


代码:

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#

【问题讨论】:

  • 迈克或我的回答是否解决了您的问题?如果是这样,请接受/投票以表达您对我们时间的赞赏。

标签: multithreading wxpython media-player media blocking


【解决方案1】:

您可能想看看 wxPython wiki,其中有几个使用线程、队列和其他有趣事物的示例:

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

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

【讨论】:

    【解决方案2】:

    您可以像任何其他多线程示例一样启动一个新线程:

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

    但是,您必须确保对 wx 的调用必须处理线程间通信。你不能只从这个新线程调用 wx-code。它会出现段错误。所以,使用wx.CallAfter

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

    【讨论】:

      猜你喜欢
      • 2016-11-29
      • 2015-12-04
      • 2013-05-20
      • 2015-04-24
      • 1970-01-01
      • 1970-01-01
      • 2014-05-24
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多