|
| 1 | +#!/usr/bin/env python |
1 | 2 | import io |
2 | 3 | import zipfile |
| 4 | +from datetime import datetime |
3 | 5 | from itertools import tee |
4 | 6 |
|
5 | 7 | import requests |
| 8 | +from tabulate import tabulate |
6 | 9 |
|
7 | 10 | __all__ = ['RemoteIOError', 'RemoteZip'] |
8 | 11 |
|
@@ -252,4 +255,45 @@ def _get_position_to_size(self): |
252 | 255 | return {a: b-a for a, b in pairwise(ilist)} |
253 | 256 |
|
254 | 257 |
|
255 | | - |
| 258 | +def list_files(url, support_suffix_range, filenames): |
| 259 | + with RemoteZip(url, headers={'User-Agent': 'remotezip'}, support_suffix_range=support_suffix_range) as zip: |
| 260 | + if len(filenames) == 0: |
| 261 | + filenames = zip.namelist() |
| 262 | + data = [('Length', 'DateTime', 'Name')] |
| 263 | + for fname in filenames: |
| 264 | + zinfo = zip.getinfo(fname) |
| 265 | + dt = datetime(*zinfo.date_time) |
| 266 | + data.append((zinfo.file_size, dt.strftime('%Y-%m-%d %H:%M:%S'), zinfo.filename)) |
| 267 | + print(tabulate(data, headers='firstrow')) |
| 268 | + |
| 269 | + |
| 270 | +def extract_files(url, support_suffix_range, filenames, path): |
| 271 | + with RemoteZip(url, support_suffix_range=support_suffix_range) as zip: |
| 272 | + if len(filenames) == 0: |
| 273 | + filenames = zip.namelist() |
| 274 | + for fname in filenames: |
| 275 | + print('Extracting {0}...'.format(fname)) |
| 276 | + zip.extract(fname, path=path) |
| 277 | + |
| 278 | + |
| 279 | +def main(): |
| 280 | + import argparse |
| 281 | + import os |
| 282 | + |
| 283 | + parser = argparse.ArgumentParser(description="Unzip remote files") |
| 284 | + parser.add_argument('url', help='Url of the zip archive') |
| 285 | + parser.add_argument('filename', nargs='*', help='File to extract') |
| 286 | + parser.add_argument('-l', '--list', action='store_true', help='List files in the archive') |
| 287 | + parser.add_argument('-d', '--dir', default=os.getcwd(), help='Extract directory, default current directory') |
| 288 | + parser.add_argument('--disable-suffix-range-support', action='store_true', help='Use when remote server does not support suffix range (negative offset)') |
| 289 | + |
| 290 | + args = parser.parse_args() |
| 291 | + support_suffix_range = not args.disable_suffix_range_support |
| 292 | + if args.list: |
| 293 | + list_files(args.url, support_suffix_range, args.filename) |
| 294 | + else: |
| 295 | + extract_files(args.url, support_suffix_range, args.filename, args.dir) |
| 296 | + |
| 297 | + |
| 298 | +if __name__ == "__main__": |
| 299 | + main() |
0 commit comments