Skip to content

Instantly share code, notes, and snippets.

@gwarser
Created February 14, 2014 21:12
Show Gist options
  • Save gwarser/9009384 to your computer and use it in GitHub Desktop.
Save gwarser/9009384 to your computer and use it in GitHub Desktop.
My backup solution :)
@echo off
rem -*- coding: cp852 -*-
cd /d %~dp0
set bck=%~d0
echo Folder kopii: %bck%
call :back c
call :back d
call :back e
call :printt Zrobione
pause
:::::::::
goto :eof
:back
call :printt %1: ¯ %bck%
xcopy %1:\* %bck%\%1\ /d /e /c /h /r /k /y /exclude:backup_all.txt 2>nul
call :chkerr
goto :eof
:chkerr
if not 0==%errorlevel% (
echo.
echo errorlevel:%errorlevel%
echo.
ping localhost -n 11 >nul
)
goto :eof
:printt
title %*
echo %*
goto :eof
\!_
\thumbs.db
\Ustawienia lokalne\Temp
\Microsoft\CardSpace
.dat.log
\NTUSER.DAT
c:\Python
c:\windows\
:\io.sys
:\msdos.sys
:\config.sys
:\pagefile.sys
:\hiberfil.sys
:\autoexec.bat
\stpd.sys
:\recycler\
:\recycled\
:\$RECYCLE.BIN\
:\Program Files\
:\System Volume Information
Microsoft\Windows\UsrClass.dat
\Dropbox\.dropbox.cache\
\Dropbox\Backup\
\Dropbox\Photos\
.default\cache\
#! /usr/bin/env python3
# -*- coding: UTF-8 -*-
from __future__ import print_function
import os, sys
import time
from shfileop import MoveToRecycleBin as rem
def p_max(line, max=78):
l = len(line)
if l < max:
return line
dots = '...'
dotslen = len(dots)
sep = os.sep
seplen = len(sep)
path, file = os.path.split(line)
filelen = len(file)
drive, dpath = os.path.splitdrive(line)
drive, dpath = drive + sep, dpath[seplen:]
drivelen = len(drive)
if filelen > max - drivelen - dotslen:
return dots.join((drive, file[-max + drivelen + dotslen:]))
#return dots.join((path[:max - filelen - dotslen - seplen], sep + file))
return dots.join((drive, dpath[-max + drivelen + dotslen:]))
def deldup(copydir, orgdir):
''' Remove files that not exists in orgdir from copydir tree (recursive)
'''
copydir = os.path.normpath(copydir)
orgdir = os.path.normpath(orgdir)
join = os.path.join
exists = os.path.exists
for root, dirs, files in os.walk(copydir, topdown=True, followlinks=False):
tmpd = root.replace(copydir, orgdir, 1)
remlist = []
for file in files:
#...filenames is a list of the names of the non-directory files in dirpath.
tmpp = join(tmpd, file)
if not exists(tmpp):
tmporg = join(root, file)
try:
print('-:', p_max(tmporg, 75))
except UnicodeEncodeError as e:
print('print error:\n', e)
with open('del_old.log', 'ba') as f:
f.write('\n'.join((tmporg, str(e), '')).encode())
remlist.append(tmporg)
for folder in dirs:
tmpp = join(tmpd, folder)
if not exists(tmpp):
tmporg = join(root, folder)
try:
print('+:', p_max(tmporg, 75))
except UnicodeEncodeError as e:
print('print error:\n', e)
with open('del_old.log', 'ba') as f:
f.write('\n'.join((tmporg, str(e), '')).encode())
remlist.append(tmporg)
if remlist:
rem('\0'.join(remlist))
def main():
dstd = os.path.splitdrive(sys.argv[0])[0]
print(dstd, os.path.splitdrive(os.getcwd())[0], os.path.splitdrive(__file__)[0])#test
#os.system('pause')
joinp = os.path.join
srcd = 'C:'
print(srcd + ' -> ' + dstd)
deldup(joinp(dstd, os.sep, srcd[0]), joinp(srcd, os.sep))
srcd = 'D:'
print(srcd + ' -> ' + dstd)
deldup(joinp(dstd, os.sep, srcd[0]), joinp(srcd, os.sep))
srcd = 'E:'
print(srcd + ' -> ' + dstd)
deldup(joinp(dstd, os.sep, srcd[0]), joinp(srcd, os.sep))
os.system('pause')
if __name__ == '__main__':
try:
main()
except KeyboardInterrupt:
pass
except:
import traceback
print('Unhandled exception:\n')
traceback.print_exc()
input('Press any key...')
#! /usr/bin/env python3
# -*- coding: UTF-8 -*-
import ctypes
import ctypes.wintypes as wintypes
__all__ = ['MoveToRecycleBin', 'SHEmptyRecycleBin', 'SHFileOperation', 'SHFILEOPSTRUCT']
class SHFILEOPSTRUCT(ctypes.Structure):
"""Contains information that the SHFileOperation function uses to perform file operations.
SHFILEOPSTRUCT{ #shfos
HWND hwnd;
UINT wFunc;
LPCSTR pFrom;
LPCSTR pTo;
FILEOP FLAGS fFlags;
BOOL fAnyOperationsAborted;
LPVOID hNameMappings;
LPCSTR lpszProgressTitle;}
wFunc (FO_*)
Operation to perform. This member can be ONE of the following values:
FO_COPY Copies the files specified by pFrom to the location specified by pTo.
FO_DELETE Deletes the files specified by pFrom (pTo is ignored).
FO_MOVE Moves the files specified by pFrom to the location specified by pTo.
FO_RENAME Renames the files specified by pFrom.
fFlags (FOF_*):
Flags that control the file operation. This member can be a COMBINATION of the following values:
FOF_ALLOWUNDO Preserves undo information, if possible.
FOF_FILESONLY Performs the operation only on files if a wildcard filename (*.*) is specified.
FOF_MULTIDESTFILES Indicates that the pTo member specifies multiple destination files (one for each source file) rather than one directory where all source files are to be deposited.
FOF_NOCONFIRMATION Responds with "yes to all" for any dialog box that is displayed.
FOF_NOCONFIRMMKDIR Does not confirm the creation of a new directory if the operation requires one to be created.
FOF_RENAMEONCOLLISION Gives the file being operated on a new name (such as "Copy #1 of...") in a move, copy, or rename operation if a file of the target name already exists.
FOF_SILENT Does not display a progress dialog box.
FOF_SIMPLEPROGRESS Displays a progress dialog box, but does not show the filenames.
FOF_WANTMAPPINGHANDLE Fills in the hNameMappings member. The handle must be freed by using the SHFreeNameMappings function.
"""
_fields_ = [
("hwnd", wintypes.HWND),
("wFunc", wintypes.UINT),
("pFrom", wintypes.LPCWSTR),
("pTo", wintypes.LPCWSTR),
("fFlags", wintypes.WORD),
("fAnyOperationsAborted", wintypes.BOOL),
("hNameMappings", wintypes.LPVOID),
("lpszProgressTitle", wintypes.LPCWSTR)]
FO_MOVE = 0x0001
FO_COPY = 0x0002
FO_DELETE = 0x0003
FO_RENAME = 0x0004
FOF_MULTIDESTFILES = 0x0001
FOF_CONFIRMMOUSE = 0x0002
FOF_SILENT = 0x0004
FOF_RENAMEONCOLLISION = 0x0008
FOF_NOCONFIRMATION = 0x0010
FOF_WANTMAPPINGHANDLE = 0x0020
FOF_ALLOWUNDO = 0x0040
FOF_FILESONLY = 0x0080
FOF_SIMPLEPROGRESS = 0x0100
FOF_NOCONFIRMMKDIR = 0x0200
FOF_NOERRORUI = 0x0400
FOF_NOCOPYSECURITYATTRIBS = 0x0800
FOF_NORECURSION = 0x1000
FOF_NO_CONNECTED_ELEMENTS = 0x2000
FOF_WANTNUKEWARNING = 0x4000
FOF_NORECURSEREPARSE = 0x8000
def SHFileOperation(shfos):
"""Performs a copy, move, rename, or delete operation on a file system object.
shfos
instance of SHFILEOPSTRUCT structure that contains information the function needs to carry out the operation
"""
SHFileOperationW = ctypes.windll.shell32.SHFileOperationW
SHFileOperationW.argtypes = (ctypes.POINTER(SHFILEOPSTRUCT),)#comma!
SHFileOperationW.restype = wintypes.INT
return SHFileOperationW(shfos)#autopointer
def SHEmptyRecycleBin(hwnd=None, pszRootPath=None, dwFlags=None):
"""Empties the Recycle Bin on the specified drive.
hwnd
A handle to the parent window of any dialog boxes that might be displayed during the operation. Default None.
pszRootPath
The string of maximum length MAX_PATH that contains the path of the root drive on which the Recycle Bin is located. It can also contain an empty string or None.
dwFlags
One or more of the following values:
SHERB_NOCONFIRMATION = 1
No dialog box confirming the deletion of the objects will be displayed.
SHERB_NOPROGRESSUI = 2
No dialog box indicating the progress will be displayed.
SHERB_NOSOUND = 4
No sound will be played when the operation is complete.
"""
SHEmptyRecycleBinW = ctypes.windll.shell32.SHEmptyRecycleBinW
SHEmptyRecycleBinW.argtypes = (wintypes.HWND, wintypes.LPCWSTR, wintypes.DWORD)
SHEmptyRecycleBinW.restype = ctypes.HRESULT
return SHEmptyRecycleBinW(hwnd, pszRootPath, dwFlags)
def MoveToRecycleBin(path):
"""Move file(s) to recycle bin.
path
string, must be path to one file, OR list of paths, separated by \0.
"""
sfops = SHFILEOPSTRUCT()
sfops.wFunc = sfops.FO_DELETE
sfops.pFrom = path + '\0\0'
sfops.fFlags = \
sfops.FOF_ALLOWUNDO|sfops.FOF_NOCONFIRMATION|sfops.FOF_NOERRORUI
SHFileOperation(sfops)
def main():
import sys, os
dpath = []
for p in sys.argv[1:]:
if os.path.exists(p):
dpath.append(p)
dpath = '\0'.join(dpath)
if dpath != '':
MoveToRecycleBin(dpath)
else:
drive = os.path.splitdrive(os.getcwd())[0]
SHEmptyRecycleBin(pszRootPath=drive, dwFlags=1)
if __name__ == "__main__":
main()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment