Tôi đang làm việc trong môi trường mà tôi không thể lưu bất kỳ thứ gì vào đĩa. Tôi cần để có thể kéo các tập tin tar và giải nén chúng mà không cần lưu vào đĩa. Điều này dường như thất bại:Sử dụng Python, làm thế nào để bạn hoàn toàn thoát khỏi bộ nhớ?
Tôi đã thử điều này, nhưng nó tung lỗi:
# fetch.py
from cStringIO import StringIO
import requests
url = "http://example.com/data.tar.gz"
response = requests.get(url)
# ERROR is thrown here. Error shown below
tar = tarfile.open(mode= "r:gz", fileobj = StringIO(response.content))
# This SHOULD break as tar.extract() saves to disk.
# Can't tell because of error on previous line of code.
data = tar.extract()
Như đã trình bày trong khối mã trên tôi nhận được traceback sau trên dòng lỗi:
Traceback (most recent call last):
File "<input>", line 1, in <module>
File "./importers/bestbuy_fetcher.py", line 23, in download_bestbuy_batch
tar = tarfile.open(mode= "r:gz", fileobj = StringIO(response.content))
File "/System/Library/Frameworks/Python.framework/Versions/2.6/lib/python2.6/tarfile.py", line 1662, in open
return func(name, filemode, fileobj, **kwargs)
File "/System/Library/Frameworks/Python.framework/Versions/2.6/lib/python2.6/tarfile.py", line 1711, in gzopen
**kwargs)
File "/System/Library/Frameworks/Python.framework/Versions/2.6/lib/python2.6/tarfile.py", line 1689, in taropen
return cls(name, mode, fileobj, **kwargs)
File "/System/Library/Frameworks/Python.framework/Versions/2.6/lib/python2.6/tarfile.py", line 1568, in __init__
self.firstmember = self.next()
File "/System/Library/Frameworks/Python.framework/Versions/2.6/lib/python2.6/tarfile.py", line 2324, in next
raise ReadError(str(e))
ReadError: invalid header
Bạn nhận được lỗi đó vì 'response.content' không phải là tệp tar được nén gzip hợp lệ – geoffspear
Điều đó có ý nghĩa: Vậy làm cách nào để biến nó thành tệp tar được nén gzip hợp lệ? – pydanny
Làm việc với tôi một tar.gz hợp lệ được phục vụ từ localhost Bạn chỉ có thể nhận được một tarball xấu. – codysoyland