How to run multiple commands synchronously from one subprocess.Popen command?
<p>Is it possible to execute an arbitrary number of commands in sequence using the same subprocess command?</p>

<p>I need each command to wait for the previous one to complete before executing and I need them all to be executed in the same session/shell. I also need this to work in Python 2.6, Python 3.5. I also need the subprocess command to work in Linux, Windows and macOS (which is why I'm just using <code>echo</code> commands as examples here).</p>

<p>See <strong>non-working</strong> code below:</p>

<pre><code>import sys
import subprocess

cmds = ['echo start', 'echo mid', 'echo end']

p = subprocess.Popen(cmd=tuple([item for item in cmds]),
                     stdout=subprocess.PIPE, stderr=subprocess.STDOUT)

for line in iter(p.stdout.readline, b''):
    sys.stdout.flush()
    print("&gt;&gt;&gt; " + line.rstrip())
</code></pre>

<p>If this is not possible, which approach should I take in order to execute my commands in synchronous sequence within the same session/shell?</p>

<p>Here is a function (and main to run it) that I use. I would say that you can use it for your problem. And it is flexible.</p>

<pre><code># processJobsInAList.py
# 2016-09-27   7:00:00 AM   Central Daylight Time 

import win32process, win32event

def CreateMyProcess2(cmd):
    ''' create process width no window that runs a command with arguments
    and returns the process handle'''
    si   = win32process.STARTUPINFO()
    info = win32process.CreateProcess(
        None,      # AppName
        cmd,       # Command line
        None,      # Process Security
        None,      # Thread Security
        0,         # inherit Handles?
        win32process.NORMAL_PRIORITY_CLASS,
        None,      # New environment
        None,      # Current directory
        si)        # startup info
    # info is tuple (hProcess, hThread, processId, threadId)
    return info[0]

if __name__ == '__main__' :
    ''' create/run a process for each list element in "cmds"
    output may be out of order because processes run concurrently '''

    cmds=["echo my","echo heart","echo belongs","echo to","echo daddy"]
    handles    = []
    for i in range(len(cmds)):
        cmd    = 'cmd /c ' + cmds[i]
        handle = CreateMyProcess2(cmd)
        handles.append(handle)

    rc = win32event.WaitForMultipleObjects( handles, 1, -1)  # 1 wait for all, -1 wait infinite
    print 'return code ',rc
</code></pre>

<p>output:<br>
heart<br>
my<br>
belongs<br>
to<br>
daddy<br>
return code  0  </p>

<p>UPDATE: If you want to run the same process, which will serialize things for you:<br>
1) Remove line:  handles.append(handle)<br>
2) Substitute the variable "handle" in place of the list "handles" on the "WaitFor" line<br>
3) Substitute WaitForSingleObject in place of WaitForMultipleObjects</p>

python subprocess python-3.5 python-2.6