python 多线程使用 fcntl flcok 处理文件

标签 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) 

我不明白为什么文件会出现乱码,我已经使用fcntl集群来保持读/写顺序,问题出在哪里?

最佳答案

这是乱码,因为 fcntl 锁属于进程,而不是线程,因此进程无法使用 fcntl 来序列化自己的访问。请参阅this answer ,例如。

您需要使用线程构造,例如 Lock相反。

关于python 多线程使用 fcntl flcok 处理文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17748450/

相关文章:

python - Alembic API 如何获取原始 SQL 脚本

c# - 这种将异步方法转换为同步方法的方法是否正确?

java - 易变和同步

java并发与scheduledexecutor和无限循环

java - Runnable 的线程在执行后不会被销毁

python - PyAudio stream_callback 意外参数

python - python 中是否有内置的自定义数字格式?

python - 在 Pyqt 中,如何通过空的小部件空间启用拖动/移动窗口?

swift 调度队列 : Serial or parallel

python - 有没有办法在 C++ 中模拟元编程?