我正在使用:
grepOut = subprocess.check_output("grep " + search + " tmp", shell=True)
要运行终端命令,我知道我可以使用 try/except 来捕获错误,但是如何获取错误代码的值?
我在官方文档上找到了这个:
exception subprocess.CalledProcessError
Exception raised when a process run by check_call() or check_output() returns a non-zero exit status.
returncode
Exit status of the child process.
但没有给出示例,谷歌也没有帮助。
最佳答案
您可以从引发的异常中获取错误代码和结果。
这可以通过 returncode
和 output
字段来完成。
例如:
import subprocess
try:
grepOut = subprocess.check_output("grep " + "test" + " tmp", shell=True)
except subprocess.CalledProcessError as grepexc:
print("error code", grepexc.returncode, grepexc.output)
关于python - subprocess.check_output 返回码,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23420990/