2015-12-03 53 views
0

我知道這個問題已經在這裏回答Python popen command. Wait until the command is finished 但事情是我不明白答案,我怎麼可以將它應用於我的代碼,所以請不要將此問題標記爲被問到之前沒有一點幫助,請:))Python popen shell命令等到子進程完成

我有一個函數,它接受一個shell命令並執行它並返回變量輸出。

它工作正常,除非我不希望控制流繼續,直到該過程已完成。原因是我正在使用imagemagick命令行工具創建圖像,當我嘗試訪問它們以獲取信息後不久就完成了。這是我的代碼..

def send_to_imagemagick(self, shell_command): 

    try: 
     # log.info('Shell command = {0}'.format(shell_command)) 
     description=os.popen(shell_command) 
     # log.info('description = {0}'.format(description))    
    except Exception as e: 
     log.info('Error with Img cmd tool {0}'.format(e)) 

    while True: 
     line = description.readline() 
     if not line: break 
     return line 

非常感謝你@Ruben這是我用來完成它,所以它正確返回輸出。

def send_to_imagemagick(self, shell_command): 

     args = shell_command.split(' ')  
     try:     
      description=Popen(args, stdout=subprocess.PIPE) 
      out, err = description.communicate() 
      return out 

     except Exception as e: 
      log.info('Error with Img cmd tool {0}'.format(e)) 
+2

爲什麼要用'os.popen'而不是'subprocess.popen'?子進程替換os.popen。 我想你想這樣做:'description.communicate()'等到它完成。 請參閱https://docs.python.org/2/library/subprocess.html#subprocess.Popen.communicate – Noxeus

+0

那麼我該如何編寫它?像這樣... description = subprocess.call([shell_command]) – whoopididoo

+0

查看我的回答.. – Noxeus

回答

3

使用subprocess.popen

該模塊旨在取代舊的幾個模塊和功能。

所以你的情況import subprocess 然後用popen.communicate()要等到你的命令完成。

有關此請參閱文檔:here

所以:

from subprocess import Popen 

def send_to_imagemagick(self, shell_command): 

    try: 
     # log.info('Shell command = {0}'.format(shell_command)) 
     description=Popen(shell_command) 
     description.communicate() 

     # log.info('description = {0}'.format(description))    
    except Exception as e: 
     log.info('Error with Img cmd tool {0}'.format(e)) 

    while True: 
     line = description.readline() 
     if not line: break 
     return line 
+0

對不起,請注意資金錯誤:) – Noxeus

+0

'return line'或'yield line'?還有,「自我」論證是否正確? –

+0

我不知道,問問OP。 – Noxeus