diff --git a/Doc/library/tarfile.rst b/Doc/library/tarfile.rst --- a/Doc/library/tarfile.rst +++ b/Doc/library/tarfile.rst @@ -586,16 +586,48 @@ A :class:`TarInfo` object also provides Return :const:`True` if it is a FIFO. .. method:: TarInfo.isdev() Return :const:`True` if it is one of character device, block device or FIFO. +.. _tarfile-commandline: + +The Command Line Interface +-------------------------- + +.. versionadded:: 3.4 + +.. cmdoption:: -l + --list + + List files in a tarfile. + +.. cmdoption:: -c + --create + + Create tarfile from source files. + + .. code-block:: bash + + $ python -m tarfile -c biggles.tar spam.txt eggs.txt + +.. cmdoption:: -t + --test + + Test if a tarfile is valid. + +.. cmdoption:: -e + --extract + + Extract tarfile into the current directory. + + .. _tar-examples: Examples -------- How to extract an entire tar archive to the current working directory:: import tarfile diff --git a/Lib/tarfile.py b/Lib/tarfile.py --- a/Lib/tarfile.py +++ b/Lib/tarfile.py @@ -2421,8 +2421,70 @@ def is_tarfile(name): t = open(name) t.close() return True except TarError: return False bltn_open = open open = TarFile.open + + +def main(): + import argparse + + config = dict(description='A simple command line interface for ' + 'tarfile module.') + parser = argparse.ArgumentParser(**config) + parser.add_argument('-l', '--list', metavar='') + parser.add_argument('-e', '--extract', metavar='') + parser.add_argument('-c', '--create', nargs='*', + metavar=('', '')) + parser.add_argument('-t', '--test', metavar='') + args = parser.parse_args() + + if args.test: + src = args.test + if is_tarfile(src): + print('{:s} is a tar archive.'.format(src)) + else: + print('{:s} is not a tar archive.'.format(src)) + + elif args.list: + with TarFile.open(args.list) as tf: + tf.list() + + elif args.extract: + tarfile_src = args.extract + with TarFile.open(tarfile_src) as tf: + tf.extractall() + print('{:s} file is extracted.'.format(tarfile_src)) + + elif args.create: + def determine_mode(mode): + try: + mode = mode.rpartition('.')[2] + except AttributeError: + return 'w' + if mode in ('gz', 'bz2', 'xz'): + mode = 'w:' + mode + elif mode == 'tgz': + mode = 'gz' + elif mode in ('tbz', 'tbz2', 'tb2'): + mode = 'bz2' + elif mode == 'txz': + mode = 'xz' + else: + mode = 'w' + return mode + + target_dir = args.create.pop(0) + mode = determine_mode(args.create) + with TarFile.open(target_dir, mode) as tf: + for file_name in args.create: + tf.add(file_name) + print('{:s} file created.'.format(target_dir)) + + else: + parser.print_help() + +if __name__ == '__main__': + main()