【问题标题】:Use python Requests to download an compressed tar.gzfile and unzip it using tar使用 python Requests 下载压缩的 tar.gz 文件并使用 tar 解压
【发布时间】:2019-06-14 19:54:16
【问题描述】:

我需要使用 request 调用来下载一个 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,因为我需要身份验证等,我必须使用请求库

【问题讨论】:

    标签: python python-requests gzip tar


    【解决方案1】:

    您只需将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())
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2011-09-01
      • 1970-01-01
      • 2013-09-04
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-05-28
      • 1970-01-01
      相关资源
      最近更新 更多