子流程check_output无法捕获某些错误

时间:2019-07-26 11:51:24

标签: python python-3.x subprocess

我的目标是将本地文件的特定块与远程存储的块进行比较。我正在尝试处理cmp返回码为1的情况,因为连接被远程主机关闭了。在这种情况下,我会重试。

以下是代码:

def cmp_bytes(local_file, remote_file, start_byte, block_size, remotIp):
    cmp_cmd = 'cmp <(tail -c +{} {} | head -c {}) <(ssh {} "tail -c +{} {} | head -c {}")'.format(start_byte, local_file, block_size, remoteIp, start_byte, remote_file, block_size)
    print(cmp_cmd)
    try:
        out = subprocess.check_output(cmp_cmd, executable='/bin/bash', shell=True, stderr=subprocess.STDOUT)
        return 0
    except subprocess.CalledProcessError as e:
        print(e.output)
        if 'closed by remote host' in str(e.output):
            return -1 #cmp failed, repeat
        return 1

有时,连接被远程主机关闭,因此cmp命令失败。我看到Connection closed by remote host打印在日志中。但是e.output并未捕获它。如何捕捉呢?

0 个答案:

没有答案