Execute piped command in Python without the shell=True option

    def exec_piped_command(self, cmd1, cmd2, cmd1stdin=None):
        print("DEBUG: Executing piped command: %s | %s" % (cmd1, cmd2))
 
        try:
            if cmd1stdin is None:
                proc1 = subprocess.Popen(cmd1, stdout=subprocess.PIPE)
                proc2 = subprocess.Popen(cmd2, stdin=proc1.stdout, stdout=subprocess.PIPE)
                commandoutput = proc2.communicate()[0]
            else:
                cmd1str = " ".join(cmd1)
                cmd2str = " ".join(cmd2)
                cmdstr = "%s | %s" % (cmd1str, cmd2str)
                proc2 = subprocess.Popen(cmdstr, stdout=subprocess.PIPE, stdin=subprocess.PIPE, shell=True)
                commandoutput = proc2.communicate(input=cmd1stdin)[0] #TODO: set the input variable, in the right way
 
            commandoutput = commandoutput.rstrip("\n")
 
            returncode = proc2.returncode
            errmsg = proc2.stderr
 
            if returncode != 0:
                raise Exception("Return code from command was not zero! Error message: %s" % errmsg)
        except Exception, e:
            print("ERROR: Piped command failed: %s | %s\nError message:" % (" ".join(cmd1), " ".join(cmd2)))
            print("ERROR %s" % str(e))
            raise
 
        return commandoutput

Tags: