1

I've read though many examples of this on StackOverflow but can't quite get it working. I'm simply trying to execute a piped command using subprocess.Popen. The challenge is that I don't know the command being submitted so need to loop as needed if it contains pipes (all the examples I've found know ahead of time how many Popens are needed..).

For example, using this command (ls | grep .py) does the following:

The first command appears to run correctly. It's return code is 0 and I can see the expected data in stdout but the 2nd Popen always exits with a returncode of 1 with no useful information in either stdout/stderr as to the problem.

Here is the code I have:

    def run_powershell_command(command, timeout_in_secs):
    try:
        cmd_split = command.split('|')
        if len(cmd_split) > 1:
            processes = []
            for x, next_cmd in enumerate(cmd_split):                                    
                next_cmd = "powershell -command \"{}\"".format(next_cmd.strip())
                if x == 0:
                    processes.append(subprocess.Popen(next_cmd, shell=True, universal_newlines=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE))
                else:
                    prev_stdout = processes[len(processes)-1].stdout
                    processes.append(subprocess.Popen(next_cmd, shell=True, universal_newlines=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE, stdin=prev_stdout))

            try:
                # kick off the LAST processes which has all sub-processes chained
                output.stdout, output.stderr = processes[len(processes)-1].communicate(timeout=int(timeout_in_secs))

                # wait for each processes to complete
                for process in processes:
                    process.wait()

                output.returncode = processes[len(processes)-1].returncode
            except subprocess.TimeoutExpired as e:
                for process in processes:
                    process.kill()

(Note: This is an internal tool so I'm not concerned with using the shell=True)

0 Answers0