Run multiple programs sequentially in one Windows command prompt?

Since you’re using Windows, you could just create a batch file listing each program you want to run which will all execute in a single console window. Since it’s a batch script you can do things like put conditional statements in it as shown in the example.

import os
import subprocess
import textwrap

# create a batch file with some commands in it
batch_filename="commands.bat"
with open(batch_filename, "wt") as batchfile:
    batchfile.write(textwrap.dedent("""
        python hello.py
        if errorlevel 1 (
            @echo non-zero exit code: %errorlevel% - terminating
            exit
        )
        time /t
        date /t
    """))

# execute the batch file as a separate process and echo its output
kwargs = dict(stdout=subprocess.PIPE, stderr=subprocess.STDOUT,
              universal_newlines=True)
with subprocess.Popen(batch_filename, **kwargs).stdout as output:
    for line in output:
        print line,

try: os.remove(batch_filename)  # clean up
except os.error: pass

Leave a Comment