使用 Python 在控制台上读取 ant 构建输出

Reading ant build output on the console with Python

我正在尝试设置一个脚本来读取 Ant 生成的输出。我的背景是我正在处理 Salesforce 代码部署和检索。这些都是用 Ant 命令完成的,结果通常会显示在屏幕上(我也可以得到一个 return 代码)。

构建成功时获取代码很容易。但是,当构建失败时,看起来像 ant return 的两个单独的 'pieces' 输出数据。不过,Python 的 subprocess.check_output 只得到第一部分。我还需要第二块,因为它是所有部署错误的注册地。

示例:

<18digitcodehere> 代替原始代码,出于安全原因。

成功

[sf:retrieve] Request for a retrieve submitted successfully.
[sf:retrieve] Request ID for the current retrieve task: <18digitcodehere>
[sf:retrieve] Waiting for server to finish processing the request...
[sf:retrieve] Request Status: Pending
[sf:retrieve] Request Status: Succeeded
[sf:retrieve] Finished request <18digitcodehere> successfully.

失败

第一部分:

[sf:deploy] Request for a deploy submitted successfully.
[sf:deploy] Request ID for the current deploy task: 0Af1a0000081rk1CAA
[sf:deploy] Waiting for server to finish processing the request...
[sf:deploy] Request Status: Pending
[sf:deploy] Request Status: Pending
[sf:deploy] Request Status: Failed

第二部分:

这个包含我想阅读的错误。而且不显示...

BUILD FAILED                                                                        
<mySystempath>\build.xml:125:                                     
*********** DEPLOYMENT FAILED ***********                                           
Request ID: <18digitcodehere>

All Component Failures:                                                             
1.  labels/CustomLabels.labels (Something) -- Error: Not in package.xml           
2.  labels/CustomLabels.labels (AnotherThing) -- Error: Not in package.xml              
3.  labels/CustomLabels.labels (Thinggy) -- Error: Not in package.xml        
4.  labels/CustomLabels.labels (YetAnotherThing) -- Error: Not in package.xml
...

我现在的脚本是这样的:

导入子进程,重新

try:
    result = subprocess.check_output(['ant', 'validatedeployment'], universal_newlines=True, shell=True)
    # I can get the code using some regex magic here

except subprocess.CalledProcessError as e:
    # the exception is thrown when the result is different from 0, I believe
    # but here I get the first part of the output, but not the second part

所以现在我可以在构建成功时获取信息(我需要获取的信息基本上是消息中的 'success'),当构建失败时我知道它失败了,但是不明白失败的真正原因。

有什么建议吗?

Ant 将错误消息写入 stderr,而不是 stdout

默认情况下,Python 的 subprocess.check_output 不捕获 stderr

要捕获 stderr,请使用以下命令:

subprocess.check_output(
    ['ant', 'validatedeployment'],
    universal_newlines=True,
    shell=True,
    stderr=subprocess.STDOUT # add this line
)