从文件中读取多进程

时间:2017-07-29 22:49:35

标签: python multiprocessing python-multiprocessing

我正在尝试从2个文件中多核读取数据,但在执行此代码后list1list2为空。

from multiprocessing import Process

def getfile(fn, out):
    print("start reading file {}".format(fn))
    with open(fn) as file:
        for line in file:
            out.append(line)

if __name__ == '__main__':
    file1 = []
    file2 = []
    p1 = Process(target=getfile, args=("100.txt", file1))
    p2 = Process(target=getfile, args=("98.txt", file2))
    p1.start()
    p2.start()

    p1.join()
    p2.join()
    print(file1)
    print(file2)

如何使用多处理从文件到列表或可迭代的内容写入数据?

1 个答案:

答案 0 :(得分:3)

使用多个流程时,请使用QueuesPipes在您的父流程与您生成的流程之间交换数据。

管道直观地允许您在父进程和子进程之间传递数据。

队列允许您的子进程在队列中存储一些数据,允许父进程检索它。

在您的情况下,队列最有意义,因为看起来您的父进程在生成后不需要将任何数据传递给子进程。

以下是一个文件的示例:

from multiprocessing import Process, Queue

def getfile(fn, out):
    with open(fn) as file:
        for line in file:
            out.put(line)

if __name__ == '__main__':
    file1 = Queue()
    p1 = Process(target=getfile, args=("100.txt", file1))
    p1.start()
    file1.get() //returns lines of the file
    p1.join()

您可以将同一个队列传递给两个进程,只需注意,如果您尝试将每个文件的内容分开,可能会在两个文件之间混合消息的顺序。

相关问题