python Python字符串比较
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/2516787/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Python string comparison
提问by ravun
I have a python function that makes a subprocess call to a shell script that outputs 'true' or 'false'. I'm storing the output from subprocess.communicate()
and trying to do return output == 'true'
but it returns False
every time. I'm not too familiar with python, but reading about string comparisons says you can compare strings using ==, !=, etc.
我有一个 python 函数,它对输出“true”或“false”的 shell 脚本进行子进程调用。我正在存储来自subprocess.communicate()
并尝试执行的输出,return output == 'true'
但它False
每次都会返回。我对 python 不太熟悉,但是阅读有关字符串比较的内容时说您可以使用 ==、!= 等来比较字符串。
Here's the code:
这是代码:
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'
The output is:
输出是:
<type 'str'> # type(isdeployed)
<type 'str'> # type('true')
true # isdeployed
but False
is always returned. I also tried return str(isdeployed) == 'true'
.
但False
总是返回。我也试过了return str(isdeployed) == 'true'
。
回答by unwind
Are you sure that there isn't a terminating line feed character, making your string contain "true\n"
? That seems likely.
您确定没有终止换行符,使您的字符串包含"true\n"
? 这似乎很有可能。
You could try return isdeployed.startswith("true")
, or some stripping.
您可以尝试 returnisdeployed.startswith("true")
或一些剥离。
回答by Tuomas Pelkonen
Have you tried to call
你有没有试过打电话
isdeployed.strip()
before the comparision
对比前