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>This one works in python 2.7 and should work also in windows. Probably some small refinement is needed for python >3. </p>

<p>The produced output is (using date and sleep it is easy to see that the commands are executed in row):</p>

<pre><code>&gt;&gt;&gt;Die Sep 27 12:47:52 CEST 2016
&gt;&gt;&gt;
&gt;&gt;&gt;Die Sep 27 12:47:54 CEST 2016
</code></pre>

<p>As you see the commands are executed in a row. </p>

<pre><code>    import sys
    import subprocess
    import shlex

    cmds = ['date', 'sleep 2', 'date']

    cmds = [shlex.split(x) for x in cmds]

    outputs =[]
    for cmd in cmds:
        outputs.append(subprocess.Popen(cmd,
                                   stdout=subprocess.PIPE, stderr=subprocess.STDOUT).communicate())


    for line in outputs:
        print "&gt;&gt;&gt;" + line[0].strip()
</code></pre>

<h3>This is what I obtain merging with @Marichyasana answer:</h3>

<pre><code>import sys
import os


def run_win_cmds(cmds):

    @Marichyasana code (+/-)

def run_unix_cmds(cmds):

    import subprocess
    import shlex


    cmds = [shlex.split(x) for x in cmds]

    outputs =[]
    for cmd in cmds:
        outputs.append(subprocess.Popen(cmd,
                                        stdout=subprocess.PIPE, stderr=subprocess.STDOUT).communicate())


    rc = ''
    for line in outputs:
        rc +=  line[0].strip()+'\n'

    return rc


cmds = ['date', 'sleep 2', 'date']

if os.name == 'nt':
     run_win_cmds(cmds)
elif os.name == 'posix':
    run_unix_cmds(cmds)
</code></pre>

<p>Ask is this one do not fit your needs! ;)</p>

python subprocess python-3.5 python-2.6