无法将子进程的解码()与字符串进行比较

Failed in compare decode() of subprocess with string

我的脚本在比较 check.decode() == 'TRUE' 时失败,/healthcheck/bin/captureFailed.sh 的结果是 TRUE,应该进入 if,而不是落入进入 else,有什么建议吗?

脚本python:

import requests
import json
from time import gmtime, strftime
import subprocess
from subprocess import Popen, PIPE, STDOUT

try:

    p = Popen(['/bin/bash', '/healthcheck/bin/captureFailed.sh'], stdout=PIPE, stdin=PIPE, stderr=STDOUT)    
    check = p.communicate()[0]
    print("[INFO] CHECK TEPS STATUS: {}".format(check.decode()))

    if str(check.decode()) == 'TRUE':

        print("[INFO] SENDING ALERT")

        webhook_url = 'https://hooks.slack.com/services/channel-here'

        response = requests.post(
            webhook_url,
            json={'text': '[ALERT] Baseline control has not been updated, there is a flaw in TEPS, check the logs. [{}]'
            .format(strftime("%Y-%m-%d", gmtime()))},
            headers={'Content-Type': 'application/json'}
        )

        if response.status_code != 200:
            raise ValueError(
                'Request to slack returned an error %s, the response is:%s'
                % (response.status_code, response.text)
            )

        else:

            print("[OK] SENT WITH SUCCESS")

    else:

        print("[OK] NO ERRORS, RUNNING SCRIPTS ...")


except Exception as e:

    print('[FAILED] Caused by: {}'.format(e))

脚本shell:

cat /healthcheck/logs/exec.log | grep HTTP | while read line
do
    echo "$line" | grep "ERROR" >/dev/null
    if [ $? = 0 ]; then
        echo "TRUE";
    fi
done

输出:

[INFO] CHECK TEPS STATUS: TRUE

[OK] NO ERRORS, RUNNING SCRIPTS ...

当使用外部命令(通过 subprocess 或其他执行)输出时,在某些其他情况下,建议不要忘记字符串(即使它们看起来 OK), 可能包含 "invisible" EOLNs.

示例:

>>> s = "abcd\n"
>>> s
'abcd\n'
>>> len(s)
5
>>> print(s)  # Looks OK
abcd

>>> s == "abcd"
False
>>> s.rstrip() == "abcd"
True

解决方法是去掉行尾,使用rstrip()
附加评论你应该只调用 decode() 一次。

下面是更正后的代码:

# ...

check = p.communicate()[0].decode()
print("[INFO] CHECK TEPS STATUS: {}".format(check))

if check.rstrip() == "TRUE":

# ...