簡體   English   中英

使用Python多重處理apply_async寫入csv會導致數據丟失

[英]Write to csv with Python Multiprocessing apply_async causes missing of data

我有一個csv文件,在其中逐行讀取url以對每個點進行請求。 解析每個請求,並將數據寫入output.csv。 這個過程是並行的。

問題與書面數據有關。 數據的某些部分被部分丟失或完全丟失(空白行)。 我想這是由於異步進程之間的沖突或沖突而發生的。 您能建議如何解決該問題。

def parse_data(url, line_num):
    print line_num, url
    r = requests.get(url)
    htmltext = r.text.encode("utf-8")
    pois = re.findall(re.compile('<pois>(.+?)</pois>'), htmltext)
    for poi in pois:
        write_data(poi)

def write_data(poi):
    with open('output.csv', 'ab') as resfile:
        writer = csv.writer(resfile)
        writer.writerow([poi])
    resfile.close()

def main():
    pool = Pool(processes=4)

    with open("input.csv", "rb") as f:
        reader = csv.reader(f)
        for line_num, line in enumerate(reader):
            url = line[0]
            pool.apply_async(parse_data, args=(url, line_num))

    pool.close()
    pool.join()

嘗試添加文件鎖定:

import fcntl

def write_data(poi):
    with open('output.csv', 'ab') as resfile:
        writer = csv.writer(resfile)
        fcntl.flock(resfile, fcntl.LOCK_EX)
        writer.writerow([poi])
        fcntl.flock(resfile, fcntl.LOCK_UN)
     # Note that you dont have to close the file. The 'with' will take care of it

並發寫入同一文件確實是導致數據丟失/文件損壞的已知原因。 此處的安全解決方案是“映射/縮小”模式-每個進程都將其寫入自己的結果文件(映射),然后將這些文件連接在一起(縮減)。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM