使用queu的python多线程处理

2024-03-28 10:08:38 发布

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

我对Python相当陌生,我需要在代码中实现多线程。在

我有一个巨大的.csv文件(百万行)作为输入。我读取这一行,对每一行发出rest请求,对每一行进行一些处理,然后将输出写入另一个文件。输入/输出文件中的行顺序很重要。现在我正在一行一行地做。 我想运行相同的代码,但并行运行,即从.csv文件中读取20行输入,然后并行进行其余的调用,这样我的程序就更快了。在

我一直在阅读http://docs.python.org/2/library/queue.html,但是我读到了pythongil问题,它说即使在多线程处理之后,代码也不会运行得更快。 有没有其他方法可以简单地实现多线程?在


Tags: 文件csv方法代码org程序resthttp
2条回答

你能把.csv文件分成多个更小的文件吗?如果可以,那么可以让另一个程序运行多个版本的处理器。在

假设这些文件都命名为file1file2,等等,您的处理器将文件名作为参数。你可以:

import subprocess
import os
import signal

for i in range(1,numfiles):
    program = subprocess.Popen(['python'], "processer.py", "file" + str(i))
    pid = program.pid

    #if you need to kill the process:
    os.kill(pid, signal.SIGINT)

Python在IO上发布GIL。如果大部分时间都花在处理rest请求上,则可以使用线程来加快处理速度:

try:
    from gevent.pool import Pool # $ pip install gevent
    import gevent.monkey; gevent.monkey.patch_all() # patch stdlib
except ImportError: # fallback on using threads
    from multiprocessing.dummy import Pool

import urllib2    

def process_line(url):
    try:
        return urllib2.urlopen(url).read(), None
    except EnvironmentError as e:
        return None, e

with open('input.csv', 'rb') as file, open('output.txt', 'wb') as outfile:
    pool = Pool(20) # use 20 concurrent connections
    for result, error in pool.imap_unordered(process_line, file):
        if error is None:
            outfile.write(result)

如果输入/输出顺序应该相同,则可以使用imap而不是{}。在

如果您的程序是CPU限制的,您可以使用创建多个进程的multiprocessing.Pool()。在

另请参见Python Interpreter blocks Multithreaded DNS requests?

This answer shows how to create a thread pool manually using threading + Queue modules。在

相关问题 更多 >