我试图从Web获取一个大文件,并将其直接流式传输到zipfile模块提供的zipfile编写器,如:
from urllib.request import urlopen
from zipfile import ZipFile
zip_file = ZipFile("/a/certain/local/zip/file.zip","a")
entry = zip_file.open("an.entry","w")
entry.write( urlopen("http://a.certain.file/on?the=web") )
Run Code Online (Sandbox Code Playgroud)
显然,这不起作用,因为.write接受一个bytes参数,而不是I/O读者.但是,由于文件相当大,我不想在压缩之前将整个文件加载到RAM中.
简单的解决方案是使用bash(从未真正尝试过,可能是错误的):
curl -s "http://a.certain.file/on?the=web" | zip -q /a/certain/local/zip/file.zip
Run Code Online (Sandbox Code Playgroud)
但是在Python脚本中放置一行bash并不是一件非常优雅,也不方便的事情.
另一个解决方案是使用urllib.request.urlretrieve下载文件,然后传递路径zipfile.ZipFile.open,但这样我仍然需要等待下载完成,此外还会消耗更多的磁盘I/O资源.
有没有办法,在Python中,直接将下载流传递给zipfile编写器,如上面的bash管道?