Github: https://github.com/RaRe-Technologies/smart_open
smart_open – Pythonで大きなファイルをストリーミングするためのutils
何?
smart_open
は、S3、HDFS、WebHDFS、HTTP、またはローカル(圧縮)ファイルとの間で非常に大きなファイルを効率的にストリーミングするためのPython 2&Python 3ライブラリです。 これは、Pythonの組み込みopen()
の代わりに使用されopen()
ているもの(100%互換、可能であればネイティブ・open
戻ってしまうもの)を何でもできます。
smart_open
は十分にテストされ、よく文書化されており、シンプルなPythonic APIを備えています:
>>> from smart_open import smart_open
>>> # stream lines from an S3 object
>>> for line in smart_open('s3://mybucket/mykey.txt', 'rb'):
... print(line.decode('utf8'))
>>> # stream from/to compressed files, with transparent (de)compression:
>>> for line in smart_open('./foo.txt.gz', encoding='utf8'):
... print(line)
>>> # can use context managers too:
>>> with smart_open('/home/radim/foo.txt.bz2', 'wb') as fout:
... fout.write(u"some content\n".encode('utf8'))
>>> with smart_open('s3://mybucket/mykey.txt', 'rb') as fin:
... for line in fin:
... print(line.decode('utf8'))
... fin.seek(0) # seek to the beginning
... b1000 = fin.read(1000) # read 1000 bytes
>>> # stream from HDFS
>>> for line in smart_open('hdfs://user/hadoop/my_file.txt', encoding='utf8'):
... print(line)
>>> # stream from HTTP
>>> for line in smart_open('http://example.com/index.html'):
... print(line)
>>> # stream from WebHDFS
>>> for line in smart_open('webhdfs://host:port/user/hadoop/my_file.txt'):
... print(line)
>>> # stream content *into* S3 (write mode):
>>> with smart_open('s3://mybucket/mykey.txt', 'wb') as fout:
... for line in [b'first line\n', b'second line\n', b'third line\n']:
... fout.write(line)
>>> # stream content *into* HDFS (write mode):
>>> with smart_open('hdfs://host:port/user/hadoop/my_file.txt', 'wb') as fout:
... for line in [b'first line\n', b'second line\n', b'third line\n']:
... fout.write(line)
>>> # stream content *into* WebHDFS (write mode):
>>> with smart_open('webhdfs://host:port/user/hadoop/my_file.txt', 'wb') as fout:
... for line in [b'first line\n', b'second line\n', b'third line\n']:
... fout.write(line)
>>> # stream using a completely custom s3 server, like s3proxy:
>>> for line in smart_open('s3u://user:secret@host:port@mybucket/mykey.txt', 'rb'):
... print(line.decode('utf8'))
>>> # you can also use a boto.s3.key.Key instance directly:
>>> key = boto.connect_s3().get_bucket("my_bucket").get_key("my_key")
>>> with smart_open(key, 'rb') as fin:
... for line in fin:
... print(line.decode('utf8'))
どうして?
AmazonのデフォルトのPythonライブラリ、 botoとboto3を使って大きなS3ファイルを扱うのは苦痛です。 そのkey.set_contents_from_string()
メソッドとkey.get_contents_as_string()
メソッドは、小さなファイル(RAMにロードされ、ストリーミングなし)に対してのみ機能します。 大きなファイルに必要なboto
のマルチパートアップロード機能を使用すると、厄介な隠された問題があり、多くの定型文があります。
smart_open
それからあなたをsmart_open
ます。 boto3上に構築されていますが、より洗練されたPythonic APIを提供します。 その結果、書くコードが少なくなり、作成するバグも少なくなります。
インストール
pip install smart_open
または、 ソースtar.gzからインストールしたい場合は、次のようにします。
python setup.py test # run unit tests python setup.py install
単体テスト(オプション)を実行するには、 モック 、 モト 、 レスポンスをインストールする必要があります。 テストはまた、コミットのプッシュ&プル要求ごとに自動的にTravis CIで実行されます。
S3固有のオプション
S3リーダーは、明らかにgzip形式のファイル(例: “.gz”で終わる)である限り、gzip形式のコンテンツを透過的にサポートします。
S3アクセスにのみ有効なキーワード引数がいくつかあります。
host引数とprofile引数の両方がキーワード引数としてboto.s3_connect()に渡されます。
>>> smart_open('s3://', host='s3.amazonaws.com')
>>> smart_open('s3://', profile_name='my-profile')
s3_session引数を使用すると、S3に接続するためのカスタムboto3.Sessionインスタンスを提供できます。
>>> smart_open('s3://', s3_session=boto3.Session())
s3_upload引数は、 initiate_multipart_uploadで受け入れられたパラメータのdictを受け取ります。
>>> smart_open('s3://', s3_upload={ 'ServerSideEncryption': 'AES256' })
S3バケット内のすべての(または選択した)キーを操作するのは非常に一般的な操作なので、これを効率的に処理する別のメソッドsmart_open.s3_iter_bucket()
もあります (マルチプロセッシングを使用してバケットキーを並列処理します )。
>>> from smart_open import smart_open, s3_iter_bucket
>>> # get all JSON files under "mybucket/foo/"
>>> bucket = boto.connect_s3().get_bucket('mybucket')
>>> for key, content in s3_iter_bucket(bucket, prefix='foo/', accept_key=lambda key: key.endswith('.json')):
... print(key, len(content))
詳細(URIのS3資格、S3の最小サイズ…)と完全なメソッドシグネチャについては、APIドキュメントをチェックしてください:
>>> import smart_open
>>> help(smart_open.smart_open_lib)
コメント、バグレポート
smart_open
はGithubに住んでいます。 問題を提出したり、要求をそこに引き出すことができます。 提案、プルリクエストと改善を歓迎します!
smart_open
は、 MITライセンスで公開されているオープンソースソフトウェアです。 Copyright(c)2015-今RadimŘehůřek 。