0

I have this table in postgres:

  remote-as           IRR-record
+==========+=====================================+
   12564   +      MAIyNT-AS38082                 +     
+==========+=====================================+
   32934   +      AS-FACEBOOK                    +
+==========+=====================================+

I want to iterate through this table and execute a command! if the command fails i want to use the second command

for row in c: #this will iterate through the table
try:
    res = subprocess.Popen('bgpq3 -4 {} -m 24 -l {}'.format(row[5],row[2]), shell=True, universal_newlines=True,
    stdout=subprocess.PIPE).communicate()[0]

except Exception:
     print("error detected")
     res = subprocess.Popen('bgpq3 -4 AS{} -m 24 -l {}'.format(row[2],row[2]), shell=True, universal_newlines=True,
     stdout=subprocess.PIPE).communicate()[0]

In some cases the first command will results in an error so the second command must be applied!

if no error occurs the result is :

ip prefix-list 38082 permit 223.27.237.0/24
ip prefix-list 38082 permit 223.27.240.0/24
ip prefix-list 38082 permit 223.27.241.0/24

the results of errors are:

ERROR:Unable to parse prefix 'MAIyNT-AS38082', af=2 (inet), ret=0
ERROR:Unable to parse prefix MAIyNT-AS38082
ERROR:Unable to add prefix MAIyNT-AS38082 (bad prefix or address-family)

The Error in this case cant be detected easily!!

Any Idea? or maybe i dont have to use try and except in this case? I have already tried almost any kind of error handling! like Except, except as, OsError and so on!!

Please note that i am able to print the error via stderr! if the results of stdout are good i want to execute the first command!!

ete eteq
  • 17
  • 4
  • Possible duplicate of [Python: "subprocess.Popen" check for success and errors](https://stackoverflow.com/questions/25079140/python-subprocess-popen-check-for-success-and-errors) – mkrieger1 Oct 09 '18 at 08:25

1 Answers1

0

You could not "catch" the exception because subprocess.Popen raise none.

If all of your error messages (the ones returned by bgpq3) start with "ERROR:" prefix you can try the code below.

for row in c:
    try:
        res = subprocess.Popen('bgpq3 -4 {} -m 24 -l {}'.format(row[5],row[2]), shell=True, universal_newlines=True,
        stdout=subprocess.PIPE).communicate()[0]

        if res.startswith("ERROR:"):
            res = subprocess.Popen('bgpq3 -4 AS{} -m 24 -l {}'.format(row[2],row[2]), shell=True, universal_newlines=True,
            stdout=subprocess.PIPE).communicate()[0]
        print(res)

     except Exception:
         print("Exception Detected for %s", row[2])