【问题标题】:apply_async callback function not being called未调用 apply_async 回调函数
【发布时间】:2016-10-20 19:31:33
【问题描述】:

我是 python 的新手,我有一个函数可以为我的数据计算特征,然后返回一个应该处理并写入文件的列表。,..我正在使用 Pool 进行计算,然后使用回调函数写入文件,但是回调函数没有被调用,我在里面放了一些打印语句,但它肯定没有被调用。 我的代码如下所示:

def write_arrow_format(results):
print("writer called")
results[1].to_csv("../data/model_data/feature-"+results[2],sep='\t',encoding='utf-8')
with open('../data/model_data/arow-'+results[2],'w') as f:
     for dic in results[0]:
         feature_list=[]
         print(dic)
         beginLine=True
         for key,value in dic.items():
              if(beginLine):
                feature_list.append(str(value))
                beginLine=False
              else:
                feature_list.append(str(key)+":"+str(value))
         feature_line=" ".join(feature_list)
         f.write(feature_line+"\n")


def generate_features(users,impressions,interactions,items,filename):
    #some processing 
    return [result1,result2,filename]





if __name__=="__main__":
   pool=mp.Pool(mp.cpu_count()-1)

   for i in range(interval):
       if i==interval:
          pool.apply_async(generate_features,(users[begin:],impressions,interactions,items,str(i)),callback=write_arrow_format)
       else:
           pool.apply_async(generate_features,(users[begin:begin+interval],impressions,interactions,items,str(i)),callback=write_arrow_format)
           begin=begin+interval
   pool.close()
   pool.join()

【问题讨论】:

  • 因为文件太长..我粘贴了有问题的代码..给出了区间变量
  • 我在您的代码中没有看到任何会阻止回调函数被调用的错误。一个好的调试技术是逐步减少你的代码,直到你有一个非常简单的例子来演示这个问题。两种非常好的事情之一将会发生:要么您将有一个可以在此处发布的 runnable 最小示例(大大增加您获得好答案的机会),或者在简化代码的过程中您将找出错误所在。
  • @unutbu 我也不知道为什么没有调用回调...所有方法都正常运行,但肯定不是回调..我尝试调试它但徒劳无功..我评论了所有除了打印之外的代码...,但仍然没有调用它
  • 也许从两端解决问题:找到成功使用多处理回调的最简单的代码。然后逐步构建该代码以执行您希望在实际脚本中完成的计算。在中间的某个地方,您会发现当前代码有什么问题。
  • @unutbu 我发现池函数(apply,apply async) 仅在一切顺利时才返回结果,否则它们会保持沉默,而不会回溯生成的进程中发生的事情bugs.python.org/issue13831Ups

标签: python python-3.x concurrency pool


【解决方案1】:

从您的帖子中,generate_features 返回的列表中包含的内容并不明显。但是,如果result1result2filename 中的任何一个都不可序列化,那么由于某种原因,多处理库将不会调用回调函数,并且不会默默地这样做。我认为这是因为多处理库会在子进程和父进程之间来回传递对象之前尝试腌制对象。如果您返回的任何内容不是“pickleable”(即不可序列化),则不会调用回调。

我自己也遇到过这个错误,结果证明它是一个给我带来麻烦的记录器对象的实例。这是一些重现我的问题的示例代码:

import multiprocessing as mp
import logging 

def bad_test_func(ii):
    print('Calling bad function with arg %i'%ii)
    name = "file_%i.log"%ii
    logging.basicConfig(filename=name,level=logging.DEBUG)
    if ii < 4:
        log = logging.getLogger()
    else:
        log = "Test log %i"%ii
    return log

def good_test_func(ii):
    print('Calling good function with arg %i'%ii)
    instance = ('hello', 'world', ii)
    return instance

def pool_test(func):
    def callback(item):
        print('This is the callback')
        print('I have been given the following item: ')
        print(item)
    num_processes = 3
    pool = mp.Pool(processes = num_processes)
    results = []
    for i in range(5):
        res = pool.apply_async(func, (i,), callback=callback)
        results.append(res)
    pool.close()
    pool.join()

def main():

    print('#'*30)
    print('Calling pool test with bad function')
    print('#'*30)

    pool_test(bad_test_func)

    print('#'*30)
    print('Calling pool test with good function')
    print('#'*30)
    pool_test(good_test_func)

if __name__ == '__main__':
    main()

希望这对您有所帮助并为您指明正确的方向。

【讨论】:

  • 天啊!!!!非常感谢 =P 另外,在回调函数中失败的任何事情似乎都会默默地失败,而不会将异常传播回日志。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-10-31
  • 1970-01-01
  • 2023-03-08
相关资源
最近更新 更多