提取Python subprocess.CalledProcessError参数列表

时间:2019-01-09 11:04:38

标签: python subprocess

以下是我们代码库中的代码段

# global library function
def check_call_noout(params, acceptable_exit_codes = (0,), shellCommand=False):
    FNULL = open('/dev/null', 'w')
    sts = 1
    try:
        if shellCommand:
            p = subprocess.Popen(params, stdout=FNULL, stderr=FNULL,shell=True)
        else:
            p = subprocess.Popen(params, stdout=FNULL, stderr=FNULL)
        sts = os.waitpid(p.pid, 0)[1]
    except:
        raise
    finally:
       FNULL.close()
       exit_code = sts >> 8
       if exit_code not in acceptable_exit_codes:
           raise subprocess.CalledProcessError(exit_code, params)

# driver code
try:
    cmd = ["/bin/tar", "--acls", "--selinux", "--xattrs", "-czf a.tar.gz", "./a.xml", "--exclude","\"lost+found\""]
    check_call_noout(cmd,(0,1),False)
except subprocess.CalledProcessError as e:
    print e.output, e.returncode
except Exception as e:
    print(type(e).__name__, e)

我想打印传递到 subprocess.CalledProcessError 对象中的params参数值,该对象在库函数内部引发并陷入我的驱动程序代码中。

但是,我无法在库函数 check_call_noout()

中进行任何更改

1 个答案:

答案 0 :(得分:2)

如果我理解正确,则获取__dict__类的subprocess.CalledProcessError属性可以:

try:
    subprocess.run([...], check=True)
except subprocess.CalledProcessError as e:
    print(e.__dict__)

您还可以使用vars函数,该函数将在内部调用__dict__

try:
    subprocess.run([...], check=True)
except subprocess.CalledProcessError as e:
    print(vars(e))