Search code examples
pythonsubprocesspopenimagemagick-convert

Python popen shell command wait till subprocess has finished


I know this question has been answered before here Python popen command. Wait until the command is finished but the thing is I don't understand the answer and how I can apply it to my code so please dont flag this question as being asked before without a little help please:)

I have a function that takes in a shell command and executes it and returns variable outputs.

It works fine except I dont want the flow of control to continue untill the process has completely finished. The reason for this is that I am creating images using the imagemagick command line tool and when I try and access them for information shortly afterward they are incomplete. This is my code..

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

Thank you so much @Ruben This is what I used to finish it off so it returns the outputs correctly.

 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))

Solution

  • Use subprocess.popen:

    This module intends to replace several older modules and functions.

    So in your case import subprocess and then use popen.communicate() to wait until your command finished.

    For the documentation on this see: here

    So:

    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