python多线程与fcntl flcok处理文件

liu*_*uan 2 python multithreading

我尝试使用python处理文本替换问题。有一个Little-endian UTF-16格式的文件,我想替换此文件中的IP地址。首先,我逐行读取此文件,然后替换目标字符串,最后,我将新字符串写入文件。但是使用多线程操作此文件时,该文件将出现乱码。这是我的代码。

import re
import codecs 
import time
import thread
import fcntl

ip = "10.200.0.1" 
searchText = r"\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}" 

def replaceFileText(fileName,searchText,replaceText,encoding):
    lines = []
    with codecs.open(fileName,"r",encoding) as file:
        fcntl.flock(file,fcntl.LOCK_EX)
        for line in file:
            lines.append(re.sub(searchText,replaceText,line))
        fcntl.flock(file,fcntl.LOCK_UN)

    with codecs.open(fileName,"w",encoding) as file:
        fcntl.flock(file,fcntl.LOCK_EX)
        for line in lines:
            file.write(line)
        fcntl.flock(file,fcntl.LOCK_UN)

def start():
    replaceFileText("rdpzhitong.rdp",searchText,ip,"utf-16-le")                                                                 
    thread.exit_thread()

def test(number):
    for n in range(number):
        thread.start_new_thread(start,())
        time.sleep(1)

test(20) 
Run Code Online (Sandbox Code Playgroud)

我不明白为什么文件出现乱码,我使用fcntl flock保持读取/写入顺序,问题出在哪里?

pil*_*row 5

这是乱码,因为fcntl锁是由进程而不是线程拥有的,因此进程不能使用fcntl序列化其自己的访问权限。例如,请参阅此答案

您将需要使用诸如Lock之类的线程构造。