2

私は Python を使い始めて 2 週間目ですが、解析して処理する必要がある圧縮/解凍されたログファイルのディレクトリに行き詰まっています。

現在、私はこれをやっています:

import os
import sys
import operator
import zipfile
import zlib
import gzip
import subprocess

if sys.version.startswith("3."):
    import io
    io_method = io.BytesIO
else:
    import cStringIO
    io_method = cStringIO.StringIO

for f in glob.glob('logs/*'):
    file = open(f,'rb')        
    new_file_name = f + "_unzipped"
    last_pos = file.tell()

    # test for gzip
    if (file.read(2) == b'\x1f\x8b'):
        file.seek(last_pos)

    #unzip to new file
    out = open( new_file_name, "wb" )
    process = subprocess.Popen(["zcat", f], stdout = subprocess.PIPE, stderr=subprocess.STDOUT)

    while True:
      if process.poll() != None:
        break;

    output = io_method(process.communicate()[0])
    exitCode = process.returncode


    if (exitCode == 0):
      print "done"
      out.write( output )
      out.close()
    else:
      raise ProcessException(command, exitCode, output)

これらの SO 回答 (ここ) とブログ投稿 (ここ)を使用して「縫い合わせ」ました

ただし、テスト ファイルが 2.5 GB であり、スクリプトが 10 分以上それを噛んでいるため、機能していないようです。

質問:
GZIP モジュールを使用せず、チャンクごとに解凍する必要がある場合 (実際のファイルは 10GB を超えています)、Python で zcat とサブプロセスを使用して解凍し、ファイルに保存するにはどうすればよいですか?

ありがとう!

4

1 に答える 1

2

これにより、logs サブディレクトリ内のすべてのファイルの最初の行が読み取られ、必要に応じて解凍されます。

#!/usr/bin/env python

import glob
import gzip
import subprocess

for f in glob.glob('logs/*'):
  if f.endswith('.gz'):
    # Open a compressed file. Here is the easy way:
    #   file = gzip.open(f, 'rb')
    # Or, here is the hard way:
    proc = subprocess.Popen(['zcat', f], stdout=subprocess.PIPE)
    file = proc.stdout
  else:
    # Otherwise, it must be a regular file
    file = open(f, 'rb')

  # Process file, for example:
  print f, file.readline()
于 2013-03-11T14:49:35.720 に答える