带有字符串的子进程的compare define()中失败

问题描述 投票:0回答:1

我的脚本在比较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))

脚本外壳:

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 ...
python string subprocess webhooks
1个回答
0
投票

使用外部命令(通过subprocess或其他命令执行)时,在某些其他情况下,建议不要忘记字符串(即使它们看起来OK)可能包含“不可见” “ EOLN s。

示例:

>>> 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 == "TRUE":

# ...
© www.soinside.com 2019 - 2024. All rights reserved.