如何在不修改库函数时获取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.CalledProcessErrorclass natively stores the command/params provided to its constructor in thecmdattribute. This is exactly theparamsvalue passed from the library function when it raises the error. - I also tweaked your
cmdlist slightly: when usingshell=False(which you're specifying), command arguments need to be individual items in the list.-czf a.tar.gzwas incorrectly combined into one string, and the quotes around"lost+found"were unnecessary since we're not invoking a shell.
内容的提问来源于stack exchange,提问作者Ibrahim Quraish
相关产品推荐
相关产品推荐

