AMayer
AMayer

Reputation: 425

Check if subprocess.getoutput command executed successfully

I have a java program that I have to run from python, get the output and store the result in 3 variables (if it works as expected, should print 3 values, each one on a different line).

This is the code that I'm using:

stdout1 = subprocess.getoutput("java -jar test.jar" + " -r " + path1)
x, y, z = stdout1.splitlines()[:]

If the path1 is not found by the test.jar program it will output a message to check the path.

Is there a way to check if the program executed correctly, and only then store the output?

x, y, z = stdout1.splitlines()[:]

Upvotes: 1

Views: 1028

Answers (2)

jfs
jfs

Reputation: 414079

You could check the returned code of the subprocess explicitly:

from subprocess import run, PIPE

process = run('java -Dfile.encoding=utf-8 -jar test.jar'.split()
              + ['-r', path], stdout=PIPE, encoding='utf-8')
if process.returncode == 0:  # success
    x, y, z = process.stdout.splitlines()

Note: this code runs java executable without starting a new shell.

The code uses the explicit utf-8 encoding to avoid depending on the default locale encoding that might not support all necessary characters.


A minimal code change in your case would be to replace getoutput() with getstatusoutput() which returns (exitcode, output) tuple and check whether exitcode is zero to determine success.

getstatusoutput() starts a new shell even if it is unnecessary and therefore it is not recommended. Also, passing path unescaped opens you to the shell command injection vulnerability if you start the shell.

getstatusoutput() calls check_output() internally and catches the exception (it is equivalent to the previous answer).

Upvotes: 2

jamylak
jamylak

Reputation: 133504

You should use

import subprocess

try:
    stdout1 = subprocess.check_output("java -jar test.jar" + " -r " + path1, shell=True)
except subprocess.CalledProcessError as e:
    # handle error

https://docs.python.org/2/library/subprocess.html#subprocess.check_output

Upvotes: 3

Related Questions