我正在 pygtk 中编写一个工具,它需要处理递归解析大目录,并将生成的匹配文件添加到列表中。这个过程显然会导致用户界面挂起,因此我尝试使用多处理库。
在我要求一些解决方案之前,请先了解一些背景知识: - 该程序有两个主要类,一个控制器类,它完成所有密集工作并与 UI 对话,一个模型类,用于处理工具所需的所有数据。
import sys
import os
import pygtk
import fnmatch
from multiprocessing import Pool
pygtk.require("2.0")
#try:
from gi.repository import Gtk
from gi.repository import GObject
#except:
# print("GTK Not Availible")
# sys.exit(1)
class Controller(object):
def __init__(self,builder,model):
self.builder=builder
self.model=model
def btn_pass_clicked(self, *args,**kwargs):
print "it's working!, its woooooorkkinnnnggg!"
spinnywheel= self.builder.get_object("activitySpinner")
spinnywheel.start()
def btn_fail_clicked(self, *args, **kwargs):
print "stopping spinnywheel!"
spinnywheel=self.builder.get_object("activitySpinner")
spinnywheel.stop()
def quit(self,*args,**kwargs):
print "iamquit"
Gtk.main_quit()
def file_menu_open(self,*args,**kwargs):
print "file->open"
self.builder.get_object("openDialogue").show()
def opendialogue_btnOpen_clicked(self,*args,**kwargs):
rootdir = os.path.expanduser(self.builder.get_object("openDialogue_entryBox").get_text())
self.builder.get_object("openDialogue").hide()
self.builder.get_object("openDialogue_entryBox").set_text("")
if os.path.exists(rootdir):
self.builder.get_object("activitySpinner").start()
print "pooling workers and walking ",rootdir
p = Pool(None)
p.apply_async(self.walk_for_files,rootdir,None,self.finished_recurse)
else:
print "Path does not exist!"
def walk_for_files(self,rootdir):
for root,dirs,files in os.walk(rootdir):
for extension in ['c','cpp']:
for filename in fnmatch.filter(files,'*.'+extension):
self.model.add_single_file(os.path.join(root,filename))
def finished_recurse(self,*args,**kargs):
print "workers finished parsing dirs!"
self.builder.get_object("activitySpinner").stop()
class Model(object):
def __init__(self):
self.fileList=[]
def add_single_file(self,file):
self.fileList.append(file)
print "added ",file
class Scrutiny(object):
def __init__(self):
builder = Gtk.Builder()
builder.add_from_file("scrutinydev.ui")
model_object=Model()
controller_object=Controller(builder,model_object)
builder.connect_signals(controller_object)
builder.get_object("windowMain").show()
builder.get_object("listView")
GObject.threads_init()
Gtk.main()
if __name__ == "__main__":
scrutiny = Scrutiny()
现在,这是我的问题。
如您所见,使用 pool() 生成的工作人员需要执行回调 finish_recurse 以便我可以在其他 UI 工作中停止 GtkSpinner。
在当前状态下的代码,我得到一个酸洗错误,
PicklingError: Can't pickle <type 'instancemethod'>: attribute lookup __builtin__.instancemethod failed
我知道这是因为我无法序列化回调,并且想要解决方法/修复的建议以实现我的需要。