Linux下Python中os.pipe()如何实现累计字节写入计数?
如何统计写入os.pipe()的累计字节数?
管道属于**非可查找(non-seekable)**的文件描述符,tell()方法依赖文件指针的定位操作,而管道本身不支持随机访问,所以调用os.fdopen(...).tell()会抛出IOError: [Errno 29] Illegal seek错误。你可以通过以下两种方式实现累计字节计数:
方法一:手动累加os.write()的返回值
每次调用os.write(fd, data)都会返回实际写入的字节数,直接维护一个计数器累加即可:
import os r, w = os.pipe() total_written = 0 # 写入数据并累加计数 total_written += os.write(w, b"hello ") total_written += os.write(w, b"world") print(f"累计写入字节数: {total_written}") # 输出 11 os.close(r) os.close(w)
方法二:自定义包装类计数
如果习惯使用文件对象的write()方法,可以封装一个带计数功能的类,在内部累加写入字节数:
import os class CountedPipeWriter: def __init__(self, fd): self.file_obj = os.fdopen(fd, 'wb') self.total_bytes = 0 def write(self, data): written = self.file_obj.write(data) self.total_bytes += written return written def __enter__(self): return self def __exit__(self, exc_type, exc_val, exc_tb): self.file_obj.close() # 使用上下文管理器确保资源释放 with os.pipe() as (r, w): with CountedPipeWriter(w) as writer: writer.write(b"hello ") writer.write(b"world") print(f"累计写入字节数: {writer.total_bytes}") # 输出 11 os.close(r)
注意事项
如果在多进程/多线程环境下使用,需要给计数器加锁(比如threading.Lock或multiprocessing.Value),避免计数出现竞态错误。
内容的提问来源于stack exchange,提问作者personal_cloud
相关产品推荐
相关产品推荐

