- 论坛徽章:
- 0
|
本帖最后由 dreamlearn 于 2012-11-23 00:48 编辑
Backup Program
有壓縮和解壓, 列出壓縮文件內容的功能
可以選擇bz或bz2壓縮或不壓縮
可以選擇忽略文件名 and 設定時間自動Backup- #!/usr/bin/python3.2
- import time
- import shutil
- import fnmatch
- import tarfile
- import os
- import re
- backupname = 'backup'+time.strftime('%Y-%m-%d-%H')
- def ignore_patterns(*patterns):
- def _ignore_patterns(path, names):
- ignore_names = [ ]
- for pattern in patterns:
- print(pattern)
- ignore_names.extend(fnmatch.filter(names, pattern))
- return set(ignore_names)
- return _ignore_patterns
-
- def TarFiles(dirfrom, dirto=None, args=None):
- global tar
- keyword = ['-n', '--not', 'gz', 'bz2', '-d', '--decompress', '-l', '--list']
- if [s for s in args if s not in ['-d', '--decompress', '-l', '--list']] :
- if '-n' in args or '--not' in args:
- tar_ext = ''
- tar_mod = ''
- elif 'bz2' in args or 'gz' in args:
- if 'bz2' in args: t_mod = 'bz2' # because args is tuple so use if to judge
- else: t_mod = 'gz'
- tar_ext = '.' + t_mod
- tar_mod = ':' + t_mod
- else:
- tar_ext = '.' + 'bz2'
- tar_mod = ':' + 'bz2'
- tar_name = '%s.tar%s' % (backupname, tar_ext)
- path_to = os.path.join(dirto, tar_name)
- if not os.path.exists(path_to):
- tar = tarfile.TarFile.open(path_to, 'w'+tar_mod)
- names = os.listdir(dirfrom)
- ig_names = [x for x in args if x not in keyword]
- if ig_names:
- print(ig_names)
- ignore = ignore_patterns(*ig_names)
- ignore_name = ignore(dirfrom, names)
- else:
- ignore_name = set( )
- for name in names:
- if name in ignore_name:
- continue
- srcname = os.path.join(dirfrom, name)
- dstname = os.path.join(dirto, name)
- if os.path.isdir(srcname):
- TarFiles(srcname, dirto, args)
- if not os.listdir(srcname):
- tar.add(srcname)
- else:
- tar.add(srcname)
-
- if '-d' in args or '--decompress' in args:
- try:
- de_tar = tarfile.TarFile.open(dirfrom, 'r')
- names = de_tar.getnames( )
- for name in names:
- de_tar.extract(name, dirto)
- de_tar.close( )
- except:
- print(sys.exc_info()[0], '\n%s' % sys.exc_info()[1])
- if '-l' in args or '--list' in args:
- tar = tarfile.TarFile.open(dirfrom)
- print(tar.list( ))
- tar.close( )
-
- def Backup(dirfrom, dirto, *args):
- for oldbackup in os.listdir(dirto):
- find = re.search(r'\bbackup\d+-\d+-\d+-\d+-', oldbackup)
- if find:
- rmpath = os.path.join(dirto, oldbackup)
- if os.path.isdir(rmpath): os.remove(rmpath)
- else: shutil.rmtree(rmpath)
- path_to = os.path.join(dirto, backupname)
- TarFiles(dirfrom, dirto, args)
-
- def AutoBackup(dirfrom, dirto, *args):
- timer = [x for x in args if '-t' and '--time' in x][0]
- if timer:
- timer = timer[-5:]
- flags = 1
- retimer = 0
- while True:
- if timer == time.strftime('%H:%M') and flags:
- TarFiles(dirfrom, dirto, args)
- if '-o' in args or '--one' in args: break
- flags = 0
- h = timer[:2]
- if timer[3] == '0':
- t = int(timer[3]) + 1
- m = int(timer[4]) + 1
- m = str(m)
- retimer = h + ':' + str(t) + m[-1]
- else:
- m = int(timer[3:]) + 1
- if m == 60: m = '00'
- retimer = h + ':' + str(m)
- if retimer == time.strftime('%H:%M'):
- flags = 1
- time.sleep(1)
-
- if __name__ == '__main__':
- Backup('/home/jack/python', '/home/jack/desktop', '*.py', '*.txt')
- tar.close( )
- '''
- print(J-Backup 1.0
- 1. Compress Files/Directorys')
- 2. Backup directorys
- 3. Auto-backup
- 4. Helps
- 5. Exit
- )
- def Main():
- try:
- print(Option)
- opt = input('>')
- except:
- print(Error includes only intege option!)
- if opt == 1:
- TarFiles(
- '''
复制代码 Search program
有顯示文件大小 and 顯示所有經過的文件路徑的功能
有通配符搜索,忽略大小寫,可以指明只搜索dir or file
也可以計算dir, file 數量, 還有可以跟據file 的修改時間去搜索- #!/usr/bin/python3.2
- import os
- import sys
- import fnmatch
- import time
- import math
- class Search(object):
- fcount = dcount = 0
- maxdepth = 0
- result = [ ]
- errors = [ ]
- def __init__(self, names, args=[]):
- # Check if defalut arg not in args will extend in args
- self.names = names
- self.args = args
-
- def search(self, path):
- ignore = False
- srcfiles = files = os.listdir(path)
- # ignore case mode so upper all file names, search names
- if 'i' in self.args or '--ignore' in self.args:
- ignore = True
- files = [f.upper( ) for f in files]
- self.names = [n.upper( ) for n in self.names]
- searchname = self._match_return_names(self.names)
- filenames = searchname(path, files)
- for file in srcfiles:
- srcname = os.path.join(path, file)
- # Dicition whether subdir if True into subdir
- if os.path.isdir(srcname):
- self.dcount += 1
- self.search(srcname)
- else:
- self.fcount += 1
- if ignore:
- file = file.upper( )
- if 'v' in self.args or '--verbose' in self.args:
- self._tryprint(srcname)
- '''
- if 'm' in self.args or '--maxdepth' in self.args:
- depth = args.index()
- '''
- if file in filenames:
- if 's' in self.args or '--size' in self.args:
- srcname = self._get_size(srcname) + ' ' + srcname
- if 'f' in self.args or '--file' in self.args\
- and os.path.isfile(srcname):
- continue
- elif 'd' in self.args or '--dir' in self.args\
- and os.path.isdir(srcname) :
- continue
- self.result.append(srcname)
- if 'c' in self.args or '--count' in self.args:
- return self.result, self.fcount, self.dcount
- else:
- return self.result
-
- def _match_return_names(self, patterns):
- def __match_return_names(path, files):
- result = [ ]
- for pattern in patterns:
- result.extend(fnmatch.filter(files, pattern))
- return result
- return __match_return_names
- def _tryprint(self, arg):
- try:
- print(arg)
- except UnicodeEncodeError:
- print(arg.encode('utf-16'))
-
- def _get_size(self, srcname):
- lst = ['Bytes', 'KB ', 'MB ', 'GB ', 'TB ', 'PB ']
- try:
- bytes = os.path.getsize(srcname)
- except OSError:
- return ('Error this file maybe Damage or not exists!\nNone')
- if bytes == 0:
- return ('0.00' + ' ' + lst[0])
- else:
- i = int(math.log(bytes, 1024))
- return ('%.3f' + ' ' + lst[i]) % (bytes / 1024 ** i)
- class Modify_Search(Search):
- tmp = [ ]
- def __init__(self, time_mod, times, names=None, args=[]):
- Search.__init__(self, names, args)
- self.time_mod = time_mod
- self.times = times * 60
- def modify_search(self, path) :
- search_time = time.time( ) - self.times
- files = os.listdir(path)
- for file in files:
- srcname = os.path.join(path, file)
- try:
- m_time = os.path.getmtime(srcname)
- except OSError:
- m_time = 0
- if os.path.isdir(srcname):
- self.modify_search(srcname)
- if self.time_mod == '--cmin':
- if self.names is not None:
- self.tmp.append(self.search(path))
- if srcname in tmp\
- and m_time > search_time:
- self.result.append(srcname)
- else:
- if m_time > search_time:
- self.result.append(srcname)
- return self.result
-
- if __name__ == '__main__':
- modify = Modify_Search('--cmin', 1)
- search = modify.modify_search('/home/jack')
- for s in search:
- print(s)
- '''
- start = time.clock( )
- search = Search(['text'], ['--ignore', '--count', '--size', '--dir'])
- print(search.search('/home/jack'))
-
- finish = time.clock( ) - start
- if len(result) > 2:
- retult, fcount, dcount = result
- fcount = 'Files: %i' % fcount
- dcount = 'Directors: %i' % dcount
- else:
- fcount = dcount = '-' * 12
- print('RESULT:--------Finished at %.3f--------%s--%s\n' % (finish, fcount, dcount))
- for r in result[0]:
- search._tryprint(r)
- '''
复制代码 |
|