1

I have a use case where I execute a java jar through python subprocess. How can I get to know if the subprocess completed successfully or terminated because of some exception. Subprocess does return an exit code but the jar does not handle returning appropriate exit codes. Is there some other way to do this?

class Test(object):
     #constructor
     .
     .
     def execute(self):
         exit_code = subprocess.call(['jar_path'])
         if not exit_code:
             return True
         else:
             return False
2
  • 1
    does the jar report correct exceptions to stdout or stderr ? Commented Sep 1, 2015 at 5:06
  • yes it does support. Commented Sep 1, 2015 at 5:59

1 Answer 1

3

Since you say -

Ques : does the jar report correct exceptions to stdout or stderr ?

Ans : yes it does support.

You can use subprocess.Popen() along with .communicate() and subprocess.PIPE to get the data from stdout/stderr and parse that appropriately to determine whether there was any exception.

Example -

 def execute(self):
     proc = subprocess.Popen(['jar_path'], stdout=subprocess.PIPE, stderr=subprocess.PIPE)
     pout,perr = proc.communicate()
     if not perr:  #or however you want to check stderr/stdout
         return True
     else:
         return False
Sign up to request clarification or add additional context in comments.

10 Comments

will it not make subprocess non blocking if I use Popen instead of call?
Well, .communicate() is blocking, it would block the process till the proc completes.
I tried with communicate. Both stderr and stdout outputs are being redirected to a file instead of PIPE. Probably because of that pout and perr seems to be none.
when you directly run that jar file in command line do you get any output in the console?
yes I do. but now inside Popen I am using file to dump stdout and stderr results. I am getting these log in a file. But pout and perr seems to be null. Is it because I am redirecting the output to a file instead of PIPE?
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.