Dan Russell
Dan Russell

Reputation: 970

Need to move on after java error when Python script uses subprocess to run a java program

In a python2.7 script, I'm using subprocess.call to run a java program like this:

java_command = "java -jar /path/to/java_program.jar %s %s >> %s" % (infile, outfile, logfile)
subprocess.call(java_command, shell=True)
...
#Do other stuff unrelated to this output

Most of the time, this works fine, but in some cases the java program errs:

Exception in thread "main" java.lang.NullPointerException
    at MyProgram.MainWindow.setProcessing(MainWindow.java:288)

The problem is that my python script is then stalled on the subprocess.call() line and can't do the "other stuff".

Is there a way I can edit either the java_command I'm using or the way I'm using subprocess to continue the python script even when the java program hangs?

Note that I can't modify the java program's code.

Upvotes: 0

Views: 95

Answers (1)

Prune
Prune

Reputation: 77837

I think you want the check_call method from that same package:

try:
    status = subprocess.check_call(java_command, shell=True)
except CalledProcessError as e:
    # The exception object contains the return code and
    # other failure information.
    ... react to the failure and recover

Upvotes: 1

Related Questions