gpt4 book ai didi

Python 字符串比较

转载 作者:太空狗 更新时间:2023-10-30 01:47:23 25 4
gpt4 key购买 nike

我有一个 python 函数,它对输出“true”或“false”的 shell 脚本进行子进程调用。我正在存储 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'

最佳答案

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

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

关于Python 字符串比较,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2516787/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com