Jake
Jake

Reputation: 249

How to prevent programmatically started python script from exiting command prompt after error?

I have to start a few different python programs every so often, so I am trying to create one "master" script that I can run that will automatically start all of the others using subprocess.Popen.

The problem I am running into is when one of the programs has an error, instead of the command prompt staying open so I can read and correct the error, it automatically closes.

Here is my code.

import subprocess
print "Starting programs"

args = "python C:\\Users\\Admin\\Desktop\\Program1.py"
subprocess.Popen(args)

args = "python C:\\Users\\Admin\\Desktop\\Program2.py"
subprocess.Popen(args)

args = "python C:\\Users\\Admin\\Desktop\\Program3.py"
subprocess.Popen(args)

I have looked into os.system as well but I couldn't find anything that would allow for this.

Upvotes: 1

Views: 141

Answers (1)

Ricardo Murillo
Ricardo Murillo

Reputation: 2865

Your code doesn't print the output of the subprocess, that is why you don't see the exception. To solve this, just add a try-except block for every program you want to run to see all exceptions and print the output of each program to see if it fails, like this:

import subprocess


def run_programs():
    try:
        args = "python C:\\Users\\Admin\\Desktop\\Program1.py"
        out = subprocess.Popen(args)
        print out
    except Exception as e:
        print 'Error in Program1.py: {}'.format(e)

    try:
        args = "python C:\\Users\\Admin\\Desktop\\Program2.py"
        out = subprocess.Popen(args)
        print out
    except Exception as e:
        print 'Error in Program2.py: {}'.format(e)


if __name__ == '__main__':
    print "Starting programs"
    run_programs()

If you want to run a lot of programs a for loop will be more practical as pointed out by Padraic.

import subprocess


def run_programs():
    cmds = [
        "python C:\\Users\\Admin\\Desktop\\Program1.py",
        "python C:\\Users\\Admin\\Desktop\\Program2.py"
        "python C:\\Users\\Admin\\Desktop\\Program3.py"
    ]
    for cmd in cmds:
        try:
            out = subprocess.Popen(cmd)
            print out
        except Exception as e:
            print 'Error in {}: {}'.format(cmd, e)

if __name__ == '__main__':
    print "Starting programs"
    run_programs()

Upvotes: 1

Related Questions