subprocess.check_output 返回码 [英] subprocess.check_output return code

查看:37
本文介绍了subprocess.check_output 返回码的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用:

grepOut = subprocess.check_output("grep " + search + " tmp", shell=True)

要运行终端命令,我知道可以使用 try/except 来捕获错误,但是如何获取错误代码的值?

To run a terminal command, I know that I can use a try/except to catch the error but how can I get the value of the error code?

我在官方文档中找到了这个:

I found this on the official documentation:

 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.

但是没有给出示例,谷歌也没有帮助.

But there are no examples given and Google was of no help.

推荐答案

您可以从引发的异常中获取错误代码和结果.

You can get the error code and results from the exception that is raised.

这可以通过 returncodeoutput 字段来完成.

This can be done through the fields returncode and 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)

这篇关于subprocess.check_output 返回码的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆