Skip to main content
 首页 » 编程设计

python之在子进程中加载 pickle

2025年05月04日9over140

所以我正在尝试 pickle 一本大字典,其中包括: NumPy 的数组, 其他词典, 文件名, 和简单的变量。

但是当我启动一个将加载数据的子进程时,我收到了“不安全的字符串 pickle”错误。

如果我在主进程调用子进程之前终止主进程,然后通过命令行手动运行它,它工作正常......

问题可能在于使用 stdout 和 stderr 进行 PIPE 处理。

我尝试过使用一些 pickle dump 协议(protocol),但无济于事。

这是我的代码示例:

    dataout = open('Dataout.pickle','wb') 
    dictout = { dict of all the values } 
    pickle.dump(dictout, dataout) 
    for i in xrange(int(self.runs)): 
        self.names.append("%s_%i"%(self.name,i)) 
        if self.rerun == 0: 
            self.chains.append(subprocess.Popen('python BaSIC_Model.py %s'%self.names[i], shell=False,stdout=subprocess.PIPE, stderr=subprocess.STDOUT,universal_newlines=True))#bufsize=0, 
 
        else: 
            self.chains.append(subprocess.Popen('python BaSIC_Model.py %s'%self.names[i], shell=False,stdout=subprocess.PIPE, stderr=subprocess.STDOUT, universal_newlines=True))#bufsize=0, 
 
    if self.Gui == 1: 
        self.cp = Cust_Progress.ProgRun("Running Chains", [0]*int(self.runs),self.itter) 
        self.cp.Play() 
        while True: 
            if not any([True if chain.poll() == None else False for chain in self.chains]): 
                print 'broke' 
                texts = [chain.stdout.read() for chain in self.chains] 
                print texts[0] 
                break 
            texts = [chain.stdout.readline() for chain in self.chains] 
            print texts[0] 
            if texts == None or None in texts: 
                texts = [0]*len(self.chains) 
            self.cp.UpdateIters(texts) 
            wx.Yield() 
            time.sleep(0.05) 
        self.cp.Done() 
        self.cp.UpdateIters(['Generating Plots']*int(self.runs)) 

从子进程开始,它失败了:

    inFile = open('Dataout.pickle','rb') 
    inputData = pickle.load(inFile) 

不安全的字符串 pickle 错误。 另外,代码中的 self.cp 是我拥有的自定义进度,它将根据每个子进程的标准输出生成进度。我有一个带线程类的工作版本,但速度慢得可怕,如果我同时运行 5 个子进程,子处理版本至少可以提高 5 倍(到 9 倍)的速度。

之前有没有其他人在子进程中加载​​ pickle 文件时遇到问题? 我有一些程序可以进行子处理并可以加载 pickle,但从来没有使用 PIPE 到 stdout。

谢谢!

请您参考如下方法:

菜鸟错误...

没有打电话:

    dataout.close() 

转储后....-_-