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>One possible solution, looks like its running in same shell:</p>

<pre><code>subprocess.Popen('echo start;echo mid;echo end', shell=True)
</code></pre>

<p>Note - If you pass your command as a string then shell has to be True
Note - This is working on linux only, you may have to find something similar way out on windows. </p>

<p>Hope it will help.</p>

<p>From python doc - </p>

<blockquote>
  <p>On Unix with shell=True, the shell defaults to /bin/sh. If args is a
  string, the string specifies the command to execute through the shell.
  This means that the string must be formatted exactly as it would be
  when typed at the shell prompt.</p>
</blockquote>

python subprocess python-3.5 python-2.6