Python字符串比较

时间:2010-03-25 15:21:41

标签: python string compare

我有一个python函数,它对shell脚本进行子进程调用,输出'true'或'false'。我正在存储subprocess.communicate()的输出并尝试执行return output == 'true',但每次都会返回False。我对python不太熟悉,但阅读字符串比较说你可以使用==,!=等来比较字符串。

以下是代码:

def verifydeployment(application):
    from subprocess import Popen, PIPE
    import socket, time

    # Loop until jboss is up.  After 90 seconds the script stops looping; this
    # causes twiddle to be unsuccessful and deployment is considered 'failed'.
    begin = time.time()
    while True:
        try:
            socket.create_connection(('localhost', 8080))
            break
        except socket.error, msg:
            if (time.time() - begin) > 90:
                break
            else:
                continue

    time.sleep(15)  # sleep for 15 seconds to allow JMX to initialize

    twiddle = os.path.join(JBOSS_DIR, 'bin', 'twiddle.sh')
    url = 'file:' + os.path.join(JBOSS_DIR, 'server', 'default', 'deploy', os.path.basename(application))

    p = Popen([twiddle, 'invoke', 'jboss.system:service=MainDeployer', 'isDeployed', url], stdout=PIPE)
    isdeployed = p.communicate()[0]

    print type(isdeployed)
    print type('true')
    print isdeployed
    return isdeployed == 'true'

输出结果为:

<type 'str'> # type(isdeployed)
<type 'str'> # type('true')
true         # isdeployed

但始终返回False。我也试过return str(isdeployed) == 'true'

2 个答案:

答案 0 :(得分:8)

您确定没有终止换行符,使您的字符串包含"true\n"吗?这似乎很可能。

你可以尝试返回isdeployed.startswith("true"),或者一些剥离。

答案 1 :(得分:6)

你试过打电话吗

isdeployed.strip()

之前的比较