小编Sup*_*ale的帖子

python multiprocessing:写入同一个excel文件

我是Python新手,我试图将五个不同进程的结果保存到一个excel文件中(每个进程写入不同的工作表)。我在这里阅读了不同的帖子,但仍然无法完成它,因为我对 pool.map、队列和锁非常困惑,而且我不确定这里需要什么来完成这项任务。到目前为止,这是我的代码:

list_of_days = ["2017.03.20", "2017.03.21", "2017.03.22", "2017.03.23", "2017.03.24"]
results = pd.DataFrame()

if __name__ == '__main__':
    global list_of_days
    writer = pd.ExcelWriter('myfile.xlsx', engine='xlsxwriter')
    nr_of_cores = multiprocessing.cpu_count()
    l = multiprocessing.Lock()
    pool = multiprocessing.Pool(processes=nr_of_cores, initializer=init, initargs=(l,))
    pool.map(f, range(len(list_of_days)))
    pool.close()
    pool.join()

def init(l):
    global lock
    lock = l

def f(k):
    global results

    *** DO SOME STUFF HERE***

    results = results[ *** finished pandas dataframe *** ]

    lock.acquire()
    results.to_excel(writer, sheet_name=list_of_days[k])
    writer.save()
    lock.release()
Run Code Online (Sandbox Code Playgroud)

结果是在 Excel 中只创建了一张工作表(我认为这是最后完成的过程)。关于这段代码的一些问题:

  • 如何避免定义全局变量?
  • 是否可以传递数据帧?
  • 我应该将锁定移至 main 吗?

非常感谢这里的一些意见,因为我认为掌握多处理是有帮助的。谢谢

python queue locking multiprocessing

5
推荐指数
1
解决办法
6455
查看次数

标签 统计

locking ×1

multiprocessing ×1

python ×1

queue ×1