我有以下Python代码在Linux机器上创建lvm快照。
#!/usr/bin/env python3.1
import subprocess
import logging
logging.basicConfig(filename='/var/log/lvsnap.log', filemode='w', level=logging.DEBUG)
lvm_vg = 'vg00-crunchbang'
lvm_name = 'root'
lvm_snapshot_size = '100'
def lvmCreateSnapshot(lvm_vg, lvm_name, lvm_snapshot_size):
return subprocess.check_call(['lvcreate', '-s', '-l', '+' + lvm_snapshot_size + '%FREE', '-n', lvm_name + '-snapshot', lvm_vg + '/' + lvm_name])
logging.debug('logging is working before lvm snapshot')
''' create lvm snapshot '''
lvm_create_snapshot = lvmCreateSnapshot(lvm_vg, lvm_name, lvm_snapshot_size)
if lvm_create_snapshot:
logging.debug('create lvm snapshot of %s/%s exited with status %s', lvm_vg, lvm_name, lvm_create_snapshot)
logging.debug('logging is working after lvm snapshot')
lvmCreateSnapshot正常运行并以0退出,然后在if语句中运行logging.debug行。 但是这不会发生,而是从脚本中收到以下输出:
> /tmp/lvmsnap.py
File descriptor 3 (/var/log/lvsnap.log) leaked on lvcreate invocation. Parent PID 7860: python3.1
Logical volume "root-snapshot" created
>
日志的输出是:
> cat /var/log/lvsnap.log
DEBUG:root:logging is working before lvm snapshot
DEBUG:root:logging is working after lvm snapshot
>
正如您所看到的那样,缺少lvm logging.debug消息(它应该出现在我创建的2条测试日志消息之间)。
为什么会发生这种情况,我该如何解决?
答案 0 :(得分:3)
您没有调用“缺失”logging.debug
,因为lvmCreateSnapshot
返回零,因此您的if
条件永远不会满足。尝试
if lvm_create_snapshot:
logging.debug('Error creating lvm snapshot of %s/%s, exited with status %s', lvm_vg, lvm_name, lvm_create_snapshot)
else:
logging.debug('created lvm snapshot of %s/%s, lvm_vg, lvm_name)
以便成功else
来电subprocess
成功,if
条件另有规定,或
if not lvm_create_snapshot:
logging.debug('...debugging text...')
仅在subprocess
返回错误时才输出调试消息。
编辑:
我刚刚查看了subprocess.check_call()
的文档,请参阅http://docs.python.org/library/subprocess.html,其中指出如果子进程调用成功,subprocess.check_call
将返回零,否则会引发CalledProcessError
异常。因此,您必须使用通常的try / except块捕获此异常。以下内容应该足够了:
try:
lvmCreateSnapshot(lvm_vg, lvm_name, lvm_snapshot_size)
logging.debug('created lvm snapshot of %s/%s', lvm_vg, lvm_name)
except CalledProcessError as e:
logging.debug('Error creating lvm snapshot of {0}/{1}. Return code was {2}'.format(lvm_vg,
lvm_name, e.returncode))
raise
最后加注是打印追溯。你当然可以使用类似return 1
的东西。