Python字符串比较

rav*_*vun 4 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'
Run Code Online (Sandbox Code Playgroud)

输出是:

<type 'str'> # type(isdeployed)
<type 'str'> # type('true')
true         # isdeployed
Run Code Online (Sandbox Code Playgroud)

但False总是返回.我也试过了return str(isdeployed) == 'true'.

unw*_*ind 8

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

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


Tuo*_*nen 6

你试过电话吗?

isdeployed.strip()
Run Code Online (Sandbox Code Playgroud)

在比较之前