2010-03-25 195 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