2015-12-03 54 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