python 多进程写入共享文件

2024-10-01 15:38:11 发布

您现在位置:Python中文网/ 问答频道 /正文

当我通过将其传递给使用多处理实现的worker函数来写入已共享的打开文件时,文件内容未正确写入。相反,“^@^@^@^@@^@@^@@^@@^@@^@^@@^@@^@^@@^@^@@^@^@^@@^@^@^@@^@^@^@^@^@^@^@^@^@^@^@^@^@^@^@^@@@^@^@@@^@^@@^@@^@^@^@@^@^@^@@^@^。在

为什么会这样?你不能让许多多处理单元写入同一个文件吗?你需要用锁吗?排队?我没有正确或有效地使用多重处理吗?在

我觉得有些示例代码可能会有所帮助,但请将其作为参考,说明我打开一个文件,并通过多重处理将打开的文件传递给另一个在该文件上编写代码的函数。在

多处理文件:

import multiprocessing as mp

class PrepWorker():
    def worker(self, open_file):
        for i in range(1,1000000):
            data = GetDataAboutI() # This function would be in a separate file
            open_file.write(data)
            open_file.flush()
        return

if __name__ == '__main__':
    open_file = open('/data/test.csv', 'w+')
    for i in range(4):
        p = mp.Process(target=PrepWorker().worker, args=(open_file,))
        jobs.append(p)
        p.start()

    for j in jobs:
        j.join()
        print '{0}.exitcode = {1}' .format(j.name, j.exitcode)   
    open_file.close()

Tags: 文件函数代码nameinfordatajobs
1条回答
网友
1楼 · 发布于 2024-10-01 15:38:11

Why would this happen?

有几个进程可能试图调用

open_file.write(data)
open_file.flush()

同时。在你看来,哪种行为是合适的,如果

  • a、 写
  • b、 写
  • a、 冲洗
  • c、 写
  • b、 冲洗

发生了什么?在

Can you not have many multiprocessing units writing to the same file? Do you need to use a Lock? A Queue?

Python multiprocessing safely writing to a file建议使用一个队列,即写入文件的“一读一读”进程。还有Writing to a file with multiprocessing和{a3}。在

相关问题 更多 >

    热门问题