Skip to content

Instantly share code, notes, and snippets.

@rako233
Created December 12, 2017 07:50
Show Gist options
  • Save rako233/d6753b082e647be76cfbcbec0f988b05 to your computer and use it in GitHub Desktop.
Save rako233/d6753b082e647be76cfbcbec0f988b05 to your computer and use it in GitHub Desktop.
#!c:\conda\python.exe
# This is a small script for backing up directories on windows. Just drop a directory in the explorer
# on this script and you get a file with the directory name which includes a time stamp.
#
# Requirements:
#
# 1) 7z must be installed with the installer
# 2) A registration of python. This is default for CPython
#
# Usage: Drag and Drop a file or directory on this script
#
import sys
import winreg
import time
import subprocess as sp
from pathlib import Path
regkey_zip = r"HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows\CurrentVersion\Uninstall\7-Zip"
msg_missing7z = """Error:\n7z must be installed with the installer or\nI can't find the path to the executable"""
msg_missingarg = """Error:\nYou must provide exact one argument!"""
msg_argfile = """Error:\nThe argument must be an readable directory or a file!"""
msg_startup = """Make a backup"""
def regkey_value(path, name="", start_key = None):
if isinstance(path, str):
path = path.split("\\")
if start_key is None:
start_key = getattr(winreg, path[0])
return regkey_value(path[1:], name, start_key)
else:
subkey = path.pop(0)
with winreg.OpenKey(start_key, subkey) as handle:
assert handle
if path:
return regkey_value(path, name, handle)
else:
desc, i = None, 0
while not desc or desc[0] != name:
desc = winreg.EnumValue(handle, i)
i += 1
return desc[1]
def msg(text):
lines = text.split('\n')
linelen = max(len(s) for s in lines)
print('+'+'-'*linelen+'+')
for line in lines:
print('|{:{length}}|'.format(line,length=linelen))
print('+' + '-' * linelen + '+')
if len(sys.argv)!=2:
msg(msg_missingarg)
_ = input('Press a key')
quit(-1)
try:
value = regkey_value(regkey_zip,'InstallLocation')
except:
msg(msg_missing7z)
_ = input('Press a key')
quit(-1)
zipper = Path(value) / '7z.exe'
try:
archive_src = Path(sys.argv[1])
if not archive_src.exists():
raise FileNotFoundError
except:
msg(msg_argfile)
_ = input('Press a key')
quit(-1)
archive_dst = archive_src.parent / Path(str(archive_src.name) + ' ' + time.strftime('%Y%m%d-%H%M%S'))
args = ['{}'.format(str(zipper)), 'a', str(archive_dst), str(archive_src)]
msg(msg_startup)
process = sp.Popen(args)
process.wait()
msg('Ready! ')
_ = input('Press a key')
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment