Python3与Python2并发写文件行为差异解析

Hazel
Hazel
发布时间:2026-10-12 | 1人浏览过
原创

本文通过代码示例对比Python3与Python2在并发写文件时的表现。测试显示,Python3(3.7.4)无论多线程还是多进程均能保证每行长度一致,无数据交错;而Python2(2.7.15)则出现行内容混合导致的长度异常。文章解析了这一版本差异背后的潜在原因及验证方法。

本文深入解析Python3环境下并发写入文件的原理,并通过详细示例代码展示具体实现过程,为相关学习与工作提供有价值的参考。

在使用Python2进行并发文件写入操作时,常遇到数据混乱现象,具体表现为某一行的内容中混入了其他行的数据片段。

然而,在Python3环境中进行并发写入时,无论是采用多进程还是多线程方式,均未出现上述数据交错问题。这是否意味着Python3具备特定的并发写入特性?

import time
import os
import multiprocessing
from multiprocessing.dummy import Pool as ThreadPool


def write(val, file):
  w = open(file, "a")
  for i in range(100):
    w.write("%s\n" % val)
    time.sleep(0.001)

def thread_write(file):
  res, pools = [], ThreadPool(10)
  for i in range(10):
    val = str(i) * 1000
    res.append(pools.apply_async(func=write, args=(val, file, )))

  while res:
    for ret in res:
      if ret.ready():
        res.remove(ret)
    time.sleep(0.01)

def mutil_write(file):
  pools = multiprocessing.Pool(processes=10)
  res = []
  for i in range(100):
    res.append(pools.apply_async(thread_write, args=(file, )))

  while res:
    for ret in res:
      if ret.ready():
        res.remove(ret)
    time.sleep(0.01)

if __name__ == '__main__':
  file = "./write_test"
  mutil_write(file)

  with open(file) as fb:
    lines = 0
    line_len = []
    for line in fb:
      lines += 1
      line = line.strip()
      line_len.append(len(line))
      if len(line) != 1000:
        raise(Exception("error line: %s, len: %d" % (line, len(line))))

    print("lines:%d, max len:%d, min:%d, avg:%.2f" % (lines, max(line_len), min(line_len), sum(line_len)/len(line_len)))
  os.remove(file)

上述代码在多进程并发写入结束后,会对每一行的长度进行校验,确保其符合预设长度。使用Python3反复运行该测试,结果均通过,未发现任何异常。

$ python3 --version
Python 3.7.4

$ python3 t.py
lines:10000, max len:1000, min:1000, avg:1000.00

若使用Python2执行相同操作,则会触发异常报错,具体表现如下:

$ python2 --version
Python 2.7.15

$ python2 t.py
Traceback (most recent call last):
 File "t.py", line 49, in <module>
  raise(Exception("error line: %s, len: %d" % (line, len(line))))
Exception: error line: 333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333330000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000, len: 1092

以上就是本文的全部内容,希望能为读者的学习带来帮助,也欢迎大家继续支持本站获取更多技术资讯。

相关标签:

本站声明

本文内容仅供参考,不代表本站观点。转载或引用请注明出处。如发现内容问题,请通过联系我们页面反馈。

Python 相关产品和应用

全部下载

专题列表