Python 使用多个核同时处理多个数据文件

Python 使用多个核同时处理多个数据文件,python,python-3.x,multicore,Python,Python 3.x,Multicore,我有多个使用python库处理的数据文件。每个文件都是一个接一个地处理的,当我查看Task manager时,只使用一个逻辑处理器(大约95%,其余在5%以内) 有办法同时处理数据文件吗? 如果是这样,有没有办法利用其他逻辑处理器来实现这一点 (欢迎编辑)您可以在不同线程或不同进程中处理不同的文件 python的优点在于,它的框架为您提供了实现这一点的工具: from multiprocessing import Process def process_panda(filename):

我有多个使用python库处理的数据文件。每个文件都是一个接一个地处理的,当我查看Task manager时,只使用一个逻辑处理器(大约95%,其余在5%以内)

有办法同时处理数据文件吗? 如果是这样,有没有办法利用其他逻辑处理器来实现这一点


(欢迎编辑)

您可以在不同线程或不同进程中处理不同的文件

python的优点在于,它的框架为您提供了实现这一点的工具:

from multiprocessing import Process

def process_panda(filename):
    # this function will be started in a different process
    process_panda_import()
    write_results()

if __name__ == '__main__':
    p1 = Process(target=process_panda, args=('file1',))
    # start process 1
    p1.start() 
    p2 = Process(target=process_panda, args=('file2',))
    # starts process 2
    p2.start() 
    # waits if process 2 is finished
    p2.join()  
    # waits if process 1 is finished
    p1.join()  
该程序将启动2个子进程,可用于处理您的文件。 当然,你可以用线程做类似的事情

您可以在此处找到文档:

在这里:


如果您的文件名在列表中,您可以使用以下代码:

from multiprocessing import Process

def YourCode(filename, otherdata):
    # Do your stuff

if __name__ == '__main__':
    #Post process files in parallel
    ListOfFilenames = ['file1','file2', ..., 'file1000']
    ListOfProcesses = []
    Processors = 20 # n of processors you want to use
    #Divide the list of files in 'n of processors' Parts
    Parts = [ListOfFilenames[i:i + Processors] for i in xrange(0, len(ListOfFilenames), Processors)]

    for part in Parts:
        for f in part:
            p = multiprocessing.Process(target=YourCode, args=(f, otherdata))
            p.start()
            ListOfProcesses.append(p)
        for p in ListOfProcesses:
            p.join()

看一看@swenzel,比我快。我们将键入准确的内容Quick note:根据:。
多处理
库将使用它。@KimKulling,向您提供代码和其他链接:)看看
concurrent.futures.ProcessPoolExecutor
——同样的想法,但仔细考虑,并在一些特殊情况下,这样的东西——Python2.7已经有七年的历史了——当它发布时已经有些过时了,因为Python3已经过时了。OP没有提到他正在使用Python2。(当然,一个建议concurrent.futures的答案必须提到它只是Python 3)你是对的。我应该说明的。我正在使用python 3.5