Advertisement
justin_hanekom

rsync-dir.py

May 13th, 2019 (edited)
279
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 4.04 KB | None | 0 0
  1. #!/usr/bin/env python
  2. # -*- coding: utf-8 -*-
  3.  
  4. from __future__ import (
  5.     absolute_import, division, print_function, unicode_literals
  6. )
  7. from nine import (
  8.     IS_PYTHON2, basestring, chr, class_types, filter, integer_types,
  9.     implements_iterator, implements_to_string, implements_repr,
  10.     input, iterkeys, iteritems, itervalues, long, map,
  11.     native_str, nine, nimport, range, range_list, reraise, str, zip
  12. )
  13.  
  14. argparse = nimport('argparse')
  15. os = nimport('os')
  16. subprocess = nimport('subprocess')
  17. time = nimport('time')
  18.  
  19.  
  20. def run():
  21.     """Runs this program.
  22.  
  23.    The program runs 'rsync' to copy files from one directory tree to another
  24.    """
  25.     start_time = time.time()
  26.     options = parse_cmd_line()
  27.     rsync_dir(
  28.         src_dir=options['srcdir'],
  29.         dest_dir=options['destdir'],
  30.         remove=options['remove'],
  31.         verbose=options['verbose'])
  32.     if options['verbose']:
  33.         print('Done, in {} seconds!'.format(time.time() - start_time))
  34.  
  35.  
  36. def parse_cmd_line():
  37.     """Parses the command-line arguments.
  38.  
  39.    Arguments:
  40.        None
  41.  
  42.    Returns:
  43.        A dictionary with each of the supplied command-line arguments.
  44.    """
  45.     parser = argparse.ArgumentParser(
  46.         description=' '.join([
  47.             'Uses rsync to recursively copy files from a source directory',
  48.             'to a destination directory']))
  49.     parser.add_argument(
  50.         'srcdir',
  51.         help='specify the directory that files will be recursively copied from')
  52.     parser.add_argument(
  53.         'destdir',
  54.         help='specify the directory that files will be recursively copied to')
  55.     parser.add_argument(
  56.         '--remove', '-r',
  57.         action='store_true',
  58.         default=False,
  59.         help=' '.join([
  60.             'specify this to remove files from the destination directory that',
  61.             'no longer exist under the source directory']))
  62.     parser.add_argument(
  63.         '--verbose', '-v',
  64.         action='store_true',
  65.         default=False,
  66.         help='specify this to display verbose output')
  67.     # vars() turns Namespace into a regular dictionary
  68.     options = vars(parser.parse_args())
  69.     options['srcdir'] = chomp_sep(options['srcdir'])
  70.     options['destdir'] = chomp_sep(options['destdir'])
  71.     return options
  72.  
  73.  
  74. def chomp_sep(dir_name):
  75.     """Removes any trailing directory separator characters from the given
  76.    directory name.
  77.  
  78.    Arguments:
  79.        dir_name: the name that has to have any trailing slashes removed
  80.  
  81.    Returns:
  82.        The directory name with no trailing separator characters
  83.    """
  84.     while dir_name.endswith(os.sep):
  85.         dir_name = dir_name[:-1]
  86.     return dir_name
  87.  
  88.  
  89. def rsync_dir(**kwargs):
  90.     """Copies files from one directory tree to another.
  91.  
  92.    Arguments:
  93.        kwargs: a dictionary with the following keys:-
  94.            src_dir:    the directory from which to recursively copy files
  95.            dest_dir:   the directory into which files are recursively copied
  96.            remove:     whether to remove files that exist in the
  97.                        dest_dir directory but not the src_dir directory
  98.            verbose:    whether to output text describing non-fatal events
  99.  
  100.    Returns:
  101.        None
  102.    """
  103.     src_dir = kwargs.pop('src_dir')
  104.     dest_dir = kwargs.pop('dest_dir')
  105.     remove = kwargs.pop('remove')
  106.     verbose = kwargs.pop('verbose')
  107.     if kwargs:
  108.         raise TypeError('Unexpected **kwargs: %r' % kwargs)
  109.     rsync_options = [
  110.         '--archive',
  111.         '--compress',
  112.         '--partial']
  113.     if remove:
  114.        rsync_options.append('--delete')
  115.     if verbose:
  116.         rsync_options.extend(['--progress', '--human-readable', '--stats'])
  117.     else:
  118.         rsync_options.append('--quiet')
  119.     subprocess.call(
  120.         'sudo rsync {} "{}/" "{}"'.format(
  121.             ' '.join(rsync_options),
  122.             src_dir,
  123.             dest_dir),
  124.         shell=True)
  125.     if verbose:
  126.         print('Performed apt-clone clone from {} to {}'.format(
  127.             src_dir,
  128.             dest_dir))
  129.  
  130.  
  131. if __name__ == '__main__':
  132.     run()
  133.  
Tags: python
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement