【问题标题】:Python - multithreading pickle.PicklingError errorPython - 多线程pickle.PicklingError错误
【发布时间】:2015-07-28 09:36:45
【问题描述】:

我正在尝试对我的一种通常可以正常工作的方法应用超时。我已经在简单的打印功能上尝试了这段代码,一切正常,但现在我遇到了错误。你能告诉我问题出在哪里吗?

方法self.check_flights 应该运行最大__TIMEOUT__ 秒。

下面的代码在一个类some_class中的方法中

            try:
                p = multiprocessing.Process(target=self.check_flights, args=(destination, start_date , end_date_2))
                p.start()
                p.join(__TIMEOUT__)
                if p.is_alive():
                    print 'TIMEOUT'
                    p.terminate()
                    p.join()

            except Exception as e:
                raise e

>ERROR: pickle.PicklingError: Can't pickle <class __main__.some_class at 0x02DD10A0>: it's not the same object as __main__.some_class

编辑:这个超时解决方案来自THIS SO answer

编辑2:为了详细说明,我附上了另一行错误:

Traceback (most recent call last):
  File "<string>", line 1, in <module>
  File "C:\Python27\lib\multiprocessing\forking.py", line 381, in main
    self = load(from_parent)
  File "C:\Python27\lib\pickle.py", line 1378, in load
    return Unpickler(file).load()
  File "C:\Python27\lib\pickle.py", line 858, in load
    dispatch[key](self)
  File "C:\Python27\lib\pickle.py", line 880, in load_eof
    raise EOFError
EOFError

【问题讨论】:

  • 你能复制/粘贴或以某种方式分享完整的课程吗?
  • 你用过if __name__ == '__main__':吗?
  • @GyörgySolymosi 是的,我确实使用过它。这是整个代码pastebin.com/uG0qSvhU

标签: python multithreading exception pickle


【解决方案1】:

这实际上是一些多进程问题,而multiprocessing 尝试腌制一些对象以有效地并行化。

如果您可以直接访问您的方法,为什么要使用如此复杂的超时方式,因此您可以在其中包含超时。

由于您唯一对时间敏感的方法是 load_whole_page 方法,因此我将修改您的代码部分,如下所示,只需省略多进程基本元素:

def load_whole_page(self,destination,start_date,end_date):
    deb()
    .
    .
    .   

    header = wait.until(EC.visibility_of_element_located((By.TAG_NAME, 'header')))
    footer = wait.until(EC.visibility_of_element_located((By.TAG_NAME, 'footer')))


    results = []
    # setting time threshold
    threshold = 10
    t = time()
    while True:
        # cheking if we reach the time we don't want to exceed.
        if (t - time()) >= threshold:
            with open('log.txt', 'a') as f:
                f.write(str(e))
                f.write(traceback.format_exc())
                print 'TIMEOUT ERROR'
            break

        wait_2.until(wait_for_more_than_n_elements((By.CSS_SELECTOR, "div.flightbox"), len(results)))

【讨论】:

  • 1.我是这方面的新手,我不知道该怎么做。
  • 2.我也不知道,在我在我的问题中发布的问题中建议。你能给我一个建议如何改进代码吗?
  • 如何在函数中包含超时?我认为这是一种更简单的方法,因为当我想打开第二个线程时,我必须调用一些函数。
  • 我可以在 check_flights 方法的每个循环中检查时间是否超过,但我担心 check_flights 中的方法 load_whole_page 也可能超过时间。
  • 首先我们尝试删除terminate()之后的所有join()并检查会发生什么。如果可以的话,请提供一些数据文件来检查我这边的代码
猜你喜欢
  • 2015-01-20
  • 1970-01-01
  • 1970-01-01
  • 2011-05-11
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-08-08
相关资源
最近更新 更多