1) Может я что-то пропустил в os и shutil, с английским у меня не очень, поэтому большая просьба опытным людям - ткните меня носом, если я что то пропустил в упомянутых модулях.
2) Можно ли добиться необходимого результата обработкой исключений, не создавая новую функцию копирования
3)Решил выложить написанную мной функцию здесь, хотелось бы услышать конструктивную критику, замечания, советы по поводу ее реализации.
Использую Python 3.0.1 (в PortablePython)
# -*- coding: cp866 -*-
import sys, subprocess, os, tempfile, code, time, shutil, stat
def dircpy(src, dst, ignore=None, symlinks=False, ForceReplace=False, logfile=None):
names = os.listdir(src)
AskStr = '\nФайл уже существует. Заменить?'
ChoiceNoReplace = ' н(n)= Не заменять (Don\'t replace)'
ChoiceReplace = ' д(y)= Да, заменить(Yes, replace)'
ChoiceAllReplace= ' в(a)= Заменить все файлы в данной директории(Replace all files in this dir)'
ChoiceForceAllReplace = ' ф(f)= Вообще все, и не спрашивайте меня больше (Force replace All, don\'t ask me never)'
ReplaceAll=False
ForceAll=ForceReplace
if ForceAll:
ReplaceAll=True
if ignore is not None:
ignored_names = ignore(src, names)
else:
ignored_names = set()
if not os.path.exists(dst):
os.makedirs(dst)
errors = []
for name in names:
if name in ignored_names:
continue
srcname = os.path.join(src, name)
dstname = os.path.join(dst, name)
try:
if symlinks and os.path.islink(srcname):
linkto = os.readlink(srcname)
os.symlink(linkto, dstname)
elif os.path.isdir(srcname):
ForceAll = dircpy(srcname, dstname, ignore, symlinks, ForceAll, logfile)
if ForceAll:
ReplaceAll=True
else:
print(dstname)
if logfile:
logfile.write('\n')
logfile.writelines(dstname)
if os.path.exists(dstname):
if ReplaceAll == True:
os.remove(dstname)
shutil.copy2(srcname, dstname)
else:
correctChoice = False
while not correctChoice:
print (AskStr)
print (ChoiceNoReplace)
print (ChoiceReplace)
print (ChoiceAllReplace)
print (ChoiceForceAllReplace)
if logfile:
logfile.writelines(AskStr)
Choice = code.InteractiveConsole.raw_input(': ')
if ('y' in Choice) or ('д' in Choice):
correctChoice = True
print ('Вы выбрали: ',ChoiceReplace)
if logfile:
logfile.writelines('\nВы выбрали: \n')
logfile.writelines(ChoiceReplace)
logfile.writelines('\n')
os.remove(dstname)
shutil.copy2(srcname, dstname)
elif ('в' in Choice) or ('a' in Choice):
correctChoice = True
print ('Вы выбрали: ',ChoiceAllReplace)
if logfile:
logfile.writelines('\nВы выбрали: \n')
logfile.writelines(ChoiceAllReplace)
logfile.writelines('\n')
os.remove(dstname)
shutil.copy2(srcname, dstname)
ReplaceAll=True
elif ('ф' in Choice) or ('f' in Choice):
correctChoice = True
print ('Вы выбрали: ',ChoiceForceAllReplace)
if logfile:
logfile.writelines('\nВы выбрали: \n')
logfile.writelines(ChoiceForceAllReplace)
logfile.writelines('\n')
os.remove(dstname)
shutil.copy2(srcname, dstname)
ReplaceAll=True
ForceAll=True
elif ('н' in Choice) or ('n' in Choice):
correctChoice = True
print ('Вы выбрали: ',ChoiceNoReplace)
if logfile:
logfile.writelines('\nВы выбрали: \n')
logfile.writelines(ChoiceNoReplace)
logfile.writelines('\n')
else:
print('Некоректный выбор\n')
if logfile:
logfile.writelines('Некоректный выбор-> ')
logfile.writelines(Choice)
logfile.writelines('\n')
else:
shutil.copy2(srcname, dstname)
# XXX What about devices, sockets etc.?
except (IOError, os.error) as why:
errors.append((srcname, dstname, str(why)))
# catch the Error from the recursive copytree so that we can
# continue with other files
except shutil.Error as err:
errors.extend(err.args[0])
try:
shutil.copystat(src, dst)
except OSError as why:
if WindowsError is not None and isinstance(why, WindowsError):
# Copying file access times may fail on Windows
pass
else:
errors.extend((src, dst, str(why)))
if errors:
raise shutil.Error(errors)
return ForceAll