流式处理大文件(s3、hdfs、gzip、bz2…)的实用程序-临时源{d}fork

srcd_smart_open的Python项目详细描述


LicenseTravis

什么?

smart_open是一个python 2&python 3库,用于从/到s3、hdfs、webhdfs、http或本地(压缩)文件的高效流式处理。它是python内置的open()的替代品:它可以做任何open可以做的事情(100%兼容,尽可能回到原生的open),加上上面很多漂亮的额外东西。

smart_open经过了很好的测试,有很好的文档记录,并且有一个简单的pythonic api:

>>>fromsmart_openimportsmart_open>>># stream lines from an S3 object>>>forlineinsmart_open('s3://mybucket/mykey.txt','rb'):...print(line.decode('utf8'))>>># stream from/to compressed files, with transparent (de)compression:>>>forlineinsmart_open('./foo.txt.gz',encoding='utf8'):...print(line)>>># can use context managers too:>>>withsmart_open('/home/radim/foo.txt.bz2','wb')asfout:...fout.write(u"some content\n".encode('utf8'))>>>withsmart_open('s3://mybucket/mykey.txt','rb')asfin:...forlineinfin:...print(line.decode('utf8'))...fin.seek(0)# seek to the beginning...b1000=fin.read(1000)# read 1000 bytes>>># stream from HDFS>>>forlineinsmart_open('hdfs://user/hadoop/my_file.txt',encoding='utf8'):...print(line)>>># stream from HTTP>>>forlineinsmart_open('http://example.com/index.html'):...print(line)>>># stream from WebHDFS>>>forlineinsmart_open('webhdfs://host:port/user/hadoop/my_file.txt'):...print(line)>>># stream content *into* S3 (write mode):>>>withsmart_open('s3://mybucket/mykey.txt','wb')asfout:...forlinein[b'first line\n',b'second line\n',b'third line\n']:...fout.write(line)>>># stream content *into* HDFS (write mode):>>>withsmart_open('hdfs://host:port/user/hadoop/my_file.txt','wb')asfout:...forlinein[b'first line\n',b'second line\n',b'third line\n']:...fout.write(line)>>># stream content *into* WebHDFS (write mode):>>>withsmart_open('webhdfs://host:port/user/hadoop/my_file.txt','wb')asfout:...forlinein[b'first line\n',b'second line\n',b'third line\n']:...fout.write(line)>>># stream using a completely custom s3 server, like s3proxy:>>>forlineinsmart_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")>>>withsmart_open(key,'rb')asfin:...forlineinfin:...print(line.decode('utf8'))>>># Stream to Digital Ocean Spaces bucket providing credentials from boto profile>>>withsmart_open('s3://bucket-for-experiments/file.txt','wb',endpoint_url='https://ams3.digitaloceanspaces.com',profile_name='digitalocean')asfout:...fout.write(b'here we stand')

为什么?

使用amazon默认的python库botoboto3处理大型s3文件是一件痛苦的事情。它的key.set_contents_from_string()key.get_contents_as_string()方法只适用于小文件(加载在RAM中,没有流)。 当使用boto的多部分上传功能(对于大型文件和大量样板文件来说是必需的)时,会有一些令人讨厌的隐藏问题。

smart_open保护你不受伤害。它建立在BOTO3的基础上,但是提供了一个更干净的pythonicAPI。这样做的结果是可以编写的代码更少,生成的错误更少。

安装

pip install smart_open

或者,如果您希望从source tar.gz安装:

python setup.py test  # run unit tests
python setup.py install

要运行单元测试(可选),还需要安装mockmotoresponsespip install mock moto responses)。测试也会在每次提交推拉请求时使用Travis CI自动运行。

支持的存档类型

smart_open允许读取和写入gzip、bzip2和xz文件。它们是透明处理的 也可以通过http、s3和其他协议。

S3特定选项

s3阅读器透明地支持gzip内容,只要密钥显然是gzip文件(例如以“.gz”结尾)。

有一些可选的关键字参数只对s3访问有用。

参数hostprofile都作为关键字参数传递给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 bucket中遍历(或选择)所有键是非常常见的操作, 还有一个额外的方法smart_open.s3_iter_bucket()可以有效地做到这一点, 并行处理存储桶键(使用多处理):

>>>fromsmart_openimportsmart_open,s3_iter_bucket>>># get all JSON files under "mybucket/foo/">>>bucket=boto.connect_s3().get_bucket('mybucket')>>>forkey,contentins3_iter_bucket(bucket,prefix='foo/',accept_key=lambdakey:key.endswith('.json')):...print(key,len(content))

有关更多信息(uri中的s3凭据,最小s3部分大小…)和完整方法签名,请查看api文档:

>>>importsmart_open>>>help(smart_open.smart_open_lib)

评论、错误报告

smart_open住在Github。你可以归档 在那里发布或拉取请求。建议,拉要求和改进欢迎!


smart_open是在MIT license下发布的开源软件。 版权所有(c)2015 NowRadim Řehůřek

欢迎加入QQ群-->: 979659372 Python中文网_新手群

推荐PyPI第三方库


热门话题
java接口中的每个方法都是抽象的,但在抽象类中,我们也只能使用抽象方法   初始化Java中声明的、未初始化的变量会发生什么情况?   java BouncyCastle openPGP将字节[]数组加密为csv文件   在Java中将类A(和所有子类)映射到类B的实例的字典   RSA公钥编码,在Java和Android中,代码相同,结果不同   java在安卓中实现数字检测语音识别   java取消选择复选框   java如何在其他配置中重用Maven配置XML片段   java有没有一种有效的方法来检查HashMap是否包含映射到相同值的键?   spring处理程序调度失败;嵌套的例外是java。lang.NoClassDefFoundError:org/apache/http/client/HttpClient   带有ehcache的java多层缓存   java如何访问chromium(或任何其他浏览器)cookie   java通过将两个集合与spring data mongodb data中的条件合并来获取计数   安卓中R.java的语法错误