python - subprocess.check_output 返回码

标签 python subprocess

我正在使用:

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.

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

最佳答案

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

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

例如:

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/

相关文章:

python - 大型门户网站上的 web2py 或 grok(zope),

python - 使用另一个列表的元素名称创建空列表

python - 用于企业 Web 应用程序的 Django

python - 命令在 shell 中有效,但在子进程中无效

linux - 在 VMware VCenter 连接自动化中运行 powershell/powercli 脚本

python - 使用 Python 运行连续的 .exe 文件

google-cloud-platform - 使用 Google Cloud Platform 的本地开发服务器导入内置模块 "_subprocess"时出错

python - 如何在 drf_yasg 中将方案从 HTTP 更改为 HTTPS?

python - 无法将每个子列表中包含 2 个元素的列表转换为单个字符串

python - 从 python 与 bash 交互