Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/277.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/github/3.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 从文件的多进程读取_Python_Multiprocessing_Python Multiprocessing - Fatal编程技术网

Python 从文件的多进程读取

Python 从文件的多进程读取,python,multiprocessing,python-multiprocessing,Python,Multiprocessing,Python Multiprocessing,我试图从2个文件中读取多核数据,但执行此代码后,list1和list2为空 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__

我试图从2个文件中读取多核数据,但执行此代码后,
list1
list2
为空

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)

如何使用多处理从要列表的文件或其他可执行的文件中获取写入数据?

当使用多个进程时,请使用
队列
管道
在父进程和生成的进程之间交换数据

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

队列允许子进程在队列上存储一些数据,从而允许父进程检索数据

在您的情况下,队列最有意义,因为您的父进程似乎不需要在其派生后将任何数据传递给子进程

以下是一个文件的示例:

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()

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

请注意,如果您试图这样做是为了提高性能,您需要注意,如果两个文件都位于同一个物理磁盘上同时读取这两个磁盘并不能使总的读取时间更快,事实上可能会使读取速度变慢,因为磁头可能会进行额外的搜索。哇!非常感谢。但是如何从两个文件中分离数据呢?创建两个队列。将不同的文件传递给每个进程,然后数据将被分离。在这种情况下,两个进程是否会分别读取整个文件?