You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在不修改库函数时获取subprocess.CalledProcessError的params参数

Solution

Since you can't modify the check_call_noout() function, you can leverage the built-in properties of the subprocess.CalledProcessError exception it raises. When the library function calls raise subprocess.CalledProcessError(exit_code, params), the params argument gets stored as the cmd attribute of the exception instance.

You can directly access this attribute in your exception handler to print the original parameters. Here's how to adjust your driver code:

# driver code
try:
    # Fixed a minor issue here: split "-czf a.tar.gz" into separate args, removed unnecessary quotes
    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 the original params passed to the exception
    print(f"Failed command parameters: {e.cmd}")
    print(f"Exit code returned: {e.returncode}")
except Exception as e:
    print(type(e).__name__, e)

Quick Explanations:

  • The subprocess.CalledProcessError class natively stores the command/params provided to its constructor in the cmd attribute. This is exactly the params value passed from the library function when it raises the error.
  • I also tweaked your cmd list slightly: when using shell=False (which you're specifying), command arguments need to be individual items in the list. -czf a.tar.gz was incorrectly combined into one string, and the quotes around "lost+found" were unnecessary since we're not invoking a shell.

内容的提问来源于stack exchange,提问作者Ibrahim Quraish

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.11 08:29:57