1

itertools.izip()複数のファイルの行を反復するために使用したいと思います。で使用するとすべてのファイルが確実に閉じられるように、コンテキスト マネージャー タイプを作成しましたwith。これはうまくいくようです:

class Files_Iterator(object):
    """Sequential line iteration from multiple files
    """
    def __init__(self, files):
        """files --> list or tuple of str, file paths
        """
        self.files = files
    def __enter__(self):
        print 'opening files'
        self.files = map(open, self.files)
        return it.izip(*self.files)
    def __exit__(self, *exception_args):
        print 'closing files'
        for arg in exception_args:
            print arg,
        for thing in self.files:
            thing.close()
        return False

2 つの質問:

  1. これを正しく実装しましたか?
  2. これをテストして、ファイルが閉じられていることを確認できますか、それとも信頼できますか?

が呼び出されたときに通知するために print ステートメントを使用しまし__exit__たが、これで十分なテストでしょうか?

>>> with Files_Iterator(['file1.txt', 'file2.txt']) as files:
    for lines in files:
        print lines
        raise Exception


opening files
('File1Line1\n', 'File2Line1\n')
closing files
<type 'exceptions.Exception'>  <traceback object at 0x0313DFD0>

Traceback (most recent call last):
  File "<pyshell#48>", line 4, in <module>
    raise Exception
Exception
>>>
4

1 に答える 1

1

はい、信頼できますが、引数に明示的に名前を付けます__exit__

def __exit__(self, exc_type, exc_value, traceback):
    print 'closing files'
    for arg in (exc_type, exc_value, traceback):
        print arg,
    for f in self.files:
        f.close()
    return False # does not suppress the exception.

そして、関数の終了時に例外があれば正常に処理されます。

于 2014-07-12T04:49:26.173 に答える