python - 使用 python Requests 下载一个压缩的 tar.gz 文件并使用 tar 解压

标签 python python-requests gzip tar

我需要使用请求调用来下载一个 tar gz 文件,我发现 requests.get 会自动解压缩该文件,我尝试使用给定的解决方案 here但是当我尝试使用 tar 解压缩它时,它说它不是 gzip 格式。

我尝试了以下方法:

response = requests.get(url,auth=(user, key),stream=True)
if response.status_code == 200:
    with open(target_path, 'wb') as f:
        f.write(response.raw)

if response.status_code == 200:
    with open(target_path, 'wb') as f:
        f.write(response.raw)

raw = response.raw
with open(target_path, 'wb') as out_file:
    while True:
        chunk = raw.read(1024, decode_content=True)
        if not chunk:
            break
        out_file.write(chunk) 

解压时出现上述所有错误:

$ tar -xvzf /tmp/file.tar.gz -C /

gzip: stdin: not in gzip format
tar: Child returned status 1
tar: Error is not recoverable: exiting now

注意:不能使用urllib.open因为我需要身份验证等,所以我必须使用请求库

最佳答案

你只需要把f.write(response.raw)改成f.write(response.raw.read())

试试下面的代码,这应该会给你一个正确的 tar gz 文件。

import requests

url = 'https://pypi.python.org/packages/source/x/xlrd/xlrd-0.9.4.tar.gz'
target_path = 'xlrd-0.9.4.tar.gz'

response = requests.get(url, stream=True)
if response.status_code == 200:
    with open(target_path, 'wb') as f:
        f.write(response.raw.read())

关于python - 使用 python Requests 下载一个压缩的 tar.gz 文件并使用 tar 解压,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54289735/

相关文章:

python - 使用 sys.argv 检索不同的函数

python - 将 Keras 集成到 SKLearn 管道?

python请求很慢

java - Android/Java 中使用 GZip 编码的 HttpGet

ubuntu - 磁带归档器和 gnuzip

python - 使用 gunicorn 时如何设置 django 测试服务器?

python - imaplib2 : imap. gmail.com 处理程序 BYE 响应:系统错误

python - 使用 curl 与 Python 请求

仅在 docker 容器内的 Python 请求 SSL 错误

python 编码 gzip 字符串