如何实现ByteCountingStreamReader?

2024-10-03 15:34:48 发布

您现在位置:Python中文网/ 问答频道 /正文

如何实现ByteCountingStreamReader?你知道吗

ByteCountingStreamReader应该包装一个文件描述符流并计算它传递的字节数。你知道吗

有点像codecs.StreamReader,但是内容不应该改变,只应该计数。你知道吗

用例:求解http://bugs.python.org/issue24259

tarfile库不会将TarInfo的文件大小与从tar读取的实际字节进行比较。你知道吗

类似于这个Java类,但是对于Python:http://commons.apache.org/proper/commons-io/apidocs/org/apache/commons/io/input/CountingInputStream.html


Tags: 文件ioorghttp内容apache用例描述符
1条回答
网友
1楼 · 发布于 2024-10-03 15:34:48

下面是一个小的包装函数,它替代了(文件)流的read方法。它还应该适用于其他类型的流,并且可以为write函数添加一个类似的包装器。你知道吗

注意:readline()似乎没有在内部使用read(),因此如果您使用它而不是普通的read(),它也必须被包装。你知道吗

def ByteCountingStreamReader(stream):
  fr = stream.read
  stream.count = 0

  def inner(size=-1):
      s = fr(size)
      stream.count += len(s)
      return s

  stream.read=inner
  return stream

# testing it
myStream = open('/etc/hosts', 'r') 
with ByteCountingStreamReader(myStream) as f:
  while True:
      s = f.read(20)
      if s == '':
          break
      print (s, end='')

  print (f.count)

相关问题 更多 >