0

I am currently trying to get the process id of a process started with subprocess.check_call.

i.e.

from subprocess import check_output

# I want to retrieve the PID of this process:
try:
    p = check_output(['some broken program']) 
except:
    if CalledProcessError: # but Popen does not throw me a CalledProcessError even if program crashes
        print("triage some stuff")
        print(p.pid) # this doesn't work unless its Popen

I have tried using Popen which works perfectly, however, it doesn't seem to be able to catch when a program is terminated i.e. CalledProcessError.

Can anyone advise, whether there is a way to get around either problem? Thanks!

caprinux
  • 46
  • 6

1 Answers1

0
  1. You have to import CalledProcessError too. Code (with check_output): from subprocess import check_output, CalledProcessError

  2. To detect a specific exception you have to use the following syntax:

     try:
         statement
     except ExceptionName:
         another_statement
    

    In your situation:

     try:
         p = check_output(['some broken program']) 
     except CalledProcessError:
         print("triage some stuff")
    
  3. You cannot reference p inside the except block as p may be undefined.

  4. Moreover, as stated in this post, subprocess.run() is recommended over subprocess.check_output()

CFV
  • 740
  • 7
  • 26
  • so... the question still stands. are there any methods that I can catch the `CalledProcessError` exception when using Popen? – caprinux Nov 27 '21 at 09:45