Python 字符串比较
我有一个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 个回答
6
你有没有试过在比较之前调用一下
isdeployed.strip()
这个呢?
8
你确定你的字符串里没有一个结束的换行符吗?这可能导致你的字符串变成了 "true\n"
。听起来很有可能。
你可以试试用 isdeployed.startswith("true")
来检查,或者先去掉多余的空格和换行。