2

我有以下 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 条测试日志消息之间)。

为什么会发生这种情况,我该如何解决?

4

1 回答 1

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

于 2011-07-11T08:16:56.547 回答