Я новичок в Python и начал писать свой первый модуль, который будет выполнять резервное копирование на внешнее хранилище (обычно один или несколько USB-дисков).
Желаемое поведение:
- проверить, установлен ли пункт назначения (резервный диск). destination_was_mounting становится True или False
- Если destination_was_mounting = False, тогда монтировать пункт назначения.
- Если mountDestination не работает, выведите исключение и перезапустите цикл.
- Если mountDestination в порядке, проверьте, существует ли контрольный файл (и backup_dir) в месте назначения.
- в случае сбоя check_destination вызовите исключение и перезапустите цикл.
- Продолжить обработку (пока не закодировали).
- При любых условиях, если destination_was_mounting = False, демонтировать пункт назначения.
Проблема в том, что если часть check_destination вызывает исключение, она не может размонтировать пункт назначения, даже если у меня это есть в разделе finally. Это как если бы destination_was_mounting становится True, даже если это должно было быть False. Или как будто check_destination выполняется до mount_destination, даже если он после него.
Мои ссылки (среди тех, кто просматривает документацию по Python и мою книгу «Learning Python»):
Python: Как указать циклу for продолжить работу с функции?
Как повторить попытку после исключения в python?
Как вернуться к циклу for после обработки исключений
#!/usr/bin/env python3.1
import sys
import os
import os.path
import subprocess
import configparser
CONFIGFILE = 'backup.ini'
# do i need this?
config = {}
config = configparser.ConfigParser()
config.read(CONFIGFILE)
backup_sources = sorted(config.sections()[1:])
class NoCheckFile(Exception):
pass
def mountDestination(destination):
return subprocess.check_call(['mount', destination])
def unMountDestination(destination):
return subprocess.check_call(['umount', destination])
def checkDestination(destination, backup_dir, checkfile):
return os.path.exists(destination + '/' + backup_dir + '/' + checkfile)
''' exception handlers '''
# perhaps add another arg like 0 or 1 for success/failure
def handleCalledProcessError(ex):
print('Exception: ' + str(ex))
def handleNoCheckFile(ex):
print('Exception: ' + str(ex))
# rename me once I work out logging
def logExecute(result):
print('Info: ' + str(result))
# can I pass logging output here
def main():
for section in backup_sources:
item = dict(config.items(section))
destination = item['destination']
destination_was_mounted = os.path.ismount(destination)
backup_dir = item['backup_dir']
checkfile = item['checkfile']
try:
''' check destination_was_mounted and mount destination if required '''
mount_destination = None
unmount_destination = None
if not destination_was_mounted:
mount_destination = mountDestination(destination)
''' check that checkfile exists in backup_dir '''
check_destination = checkDestination(destination, backup_dir, checkfile)
if not check_destination:
raise NoCheckFile('no checkfile found')
''' lvm snapshot, mount and source path update '''
''' backup engine code here '''
''' check destination_was_mounted and um-mount destination if required '''
if not destination_was_mounted:
unmount_destination = unMountDestination(destination)
except subprocess.CalledProcessError as ex:
print(destination, 'mounted before loop start: ', destination_was_mounted)
handleCalledProcessError(ex)
except NoCheckFile as ex:
handleNoCheckFile(ex)
else:
print(destination, 'mounted before loop start: ', destination_was_mounted)
logExecute(mount_destination)
logExecute(check_destination)
finally:
print('should always see me')
logExecute(unmount_destination)
# return to say True or False
# this should be where email reports etc. go
if __name__ == '__main__':
main()
Соответствующие части файла backup.ini:
[general]
[1]
DESTINATION = /mnt/backup2
BACKUP_DIR = BACKUP2
CHECKFILE = .checkfile
[2]
DESTINATION = /mnt/backup1
BACKUP_DIR = BACKUP1
CHECKFILE = .checkfile
Вывод выглядит так: у меня есть 2 резервных диска, подключенных в точках монтирования, указанных в [1] и [2], и я намеренно не создал контрольный файл для [1] для тестирования.
> umount /mnt/backup1
umount: /mnt/backup1: not mounted
> umount /mnt/backup2
umount: /mnt/backup2: not mounted
> mugsyback.py
Exception: no checkfile found
should always see me
Info: None
/mnt/backup1 mounted before loop start: False
Info: 0
Info: True
should always see me
Info: 0
> mount
...
/dev/sdc1 on /mnt/backup2 type ext3 (rw)