簡體   English   中英

使用python請求下載壓縮的tar.gzfile並使用tar解壓縮

[英]Use python Requests to download an compressed tar.gzfile and unzip it using tar

我需要使用請求調用來下載tar gz文件,我發現request.get自動解壓縮了文件,我嘗試使用此處提供的解決方案但是當我嘗試使用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())

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM