2010-03-25 172 views
4

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

+0

你肯定有后“真正的”无新线之前调用

isdeployed.strip() 

?也许试试isdeployed.strip()=='true' – 2010-03-25 15:32:20

回答

8

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

您可以尝试返回isdeployed.startswith("true")或某些剥离。

+0

哦,有。这是一个简单的问题,它一直在困扰着我。谢谢! – ravun 2010-03-25 15:26:33

6

您是否尝试过比较

+0

我没注意到换行符。我将使用strip()函数。谢谢! – ravun 2010-03-25 15:26:59