Last active
September 25, 2015 02:57
-
-
Save danielrichman/851463 to your computer and use it in GitHub Desktop.
random python periodic backup
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/usr/bin/python | |
# Copyright 2011 (C) Daniel Richman | |
# | |
# This programme is free software: you can redistribute it and/or modify | |
# it under the terms of the GNU General Public License as published by | |
# the Free Software Foundation, either version 3 of the License, or | |
# (at your option) any later version. | |
# | |
# This programme is distributed in the hope that it will be useful, | |
# but WITHOUT ANY WARRANTY; without even the implied warranty of | |
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the | |
# GNU General Public License for more details. | |
# | |
# You should have received a copy of the GNU General Public License | |
# along with this programme. If not, see <http://www.gnu.org/licenses/>. | |
import sys | |
import os | |
import time | |
import shutil | |
import traceback | |
usage = "Usage: {0} <source> <backup directory> <period in minutes>" | |
def main(): | |
if len(sys.argv) != 4: | |
print usage.format(sys.argv[0]) | |
return False | |
source = os.path.abspath(sys.argv[1]) | |
backup_dir = os.path.abspath(sys.argv[2]) | |
if not os.path.isdir(source): | |
print "Bad source path" | |
return False | |
if not os.path.isdir(backup_dir): | |
print "Bad backup_dir" | |
return False | |
try: | |
period = int(sys.argv[3]) | |
assert period > 0 | |
except: | |
print "Bad period value" | |
return False | |
print "Backing up from: {0}".format(source) | |
print "Backing up to: {0}".format(backup_dir) | |
print "Every {0} minutes.".format(period) | |
try: | |
while True: | |
caught_backup(source, backup_dir) | |
time.sleep(period )#* 60) | |
except KeyboardInterrupt: | |
print "Caught Ctrl-C; exiting." | |
return True | |
def caught_backup(source, backup_dir): | |
try: | |
backup(source, backup_dir) | |
except: | |
print "Something went wrong: " | |
traceback.print_exc() | |
print "Backup failed" | |
print "" | |
def backup(source, backup_dir): | |
print "Backup time!" | |
dest = os.path.join(backup_dir, backup_name(source)) | |
print "Copying '{0}' to '{1}'".format(source, dest) | |
shutil.copytree(source, dest) | |
print "Backup done" | |
def backup_name(source): | |
return time.strftime("%Y%m%d_%H%M%S", time.gmtime()) | |
if __name__ == "__main__": | |
try: | |
retval = main() | |
except: | |
print "The program crashed. This is bad." | |
sys.exit(1) | |
sys.exit(retval) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment