(args=None)
| 2516 | |
| 2517 | |
| 2518 | def main(args=None): |
| 2519 | import argparse |
| 2520 | |
| 2521 | description = 'A simple command-line interface for zipfile module.' |
| 2522 | parser = argparse.ArgumentParser(description=description) |
| 2523 | group = parser.add_mutually_exclusive_group(required=True) |
| 2524 | group.add_argument('-l', '--list', metavar='<zipfile>', |
| 2525 | help='Show listing of a zipfile') |
| 2526 | group.add_argument('-e', '--extract', nargs=2, |
| 2527 | metavar=('<zipfile>', '<output_dir>'), |
| 2528 | help='Extract zipfile into target dir') |
| 2529 | group.add_argument('-c', '--create', nargs='+', |
| 2530 | metavar=('<name>', '<file>'), |
| 2531 | help='Create zipfile from sources') |
| 2532 | group.add_argument('-t', '--test', metavar='<zipfile>', |
| 2533 | help='Test if a zipfile is valid') |
| 2534 | parser.add_argument('--metadata-encoding', metavar='<encoding>', |
| 2535 | help='Specify encoding of member names for -l, -e and -t') |
| 2536 | args = parser.parse_args(args) |
| 2537 | |
| 2538 | encoding = args.metadata_encoding |
| 2539 | |
| 2540 | if args.test is not None: |
| 2541 | src = args.test |
| 2542 | with ZipFile(src, 'r', metadata_encoding=encoding) as zf: |
| 2543 | badfile = zf.testzip() |
| 2544 | if badfile: |
| 2545 | print("The following enclosed file is corrupted: {!r}".format(badfile)) |
| 2546 | print("Done testing") |
| 2547 | |
| 2548 | elif args.list is not None: |
| 2549 | src = args.list |
| 2550 | with ZipFile(src, 'r', metadata_encoding=encoding) as zf: |
| 2551 | zf.printdir() |
| 2552 | |
| 2553 | elif args.extract is not None: |
| 2554 | src, curdir = args.extract |
| 2555 | with ZipFile(src, 'r', metadata_encoding=encoding) as zf: |
| 2556 | zf.extractall(curdir) |
| 2557 | |
| 2558 | elif args.create is not None: |
| 2559 | if encoding: |
| 2560 | print("Non-conforming encodings not supported with -c.", |
| 2561 | file=sys.stderr) |
| 2562 | sys.exit(1) |
| 2563 | |
| 2564 | zip_name = args.create.pop(0) |
| 2565 | files = args.create |
| 2566 | |
| 2567 | def addToZip(zf, path, zippath): |
| 2568 | if os.path.isfile(path): |
| 2569 | zf.write(path, zippath, ZIP_DEFLATED) |
| 2570 | elif os.path.isdir(path): |
| 2571 | if zippath: |
| 2572 | zf.write(path, zippath) |
| 2573 | for nm in sorted(os.listdir(path)): |
| 2574 | addToZip(zf, |
| 2575 | os.path.join(path, nm), os.path.join(zippath, nm)) |
no test coverage detected