curious07
curious07

Reputation: 31

python run list of functions untill one passes

I run a command using python in linux, and I have a several different method of verifying based on system type. My question is can I make the verify function take a list of functions instead creating all the combinations.

currently I have:

def verify_A(*args):
    checks the commands was successful using method A

def verify_B(*args):
    checks the commands was successful using method B

def run_command(*args)
    runs the commands on linux terminal, no checking

def run_and_verify_A(*args):
     run_command(*args)
     verify_A(*args)

def run_and_verify_B(*args):
    run_command(*args)
    verify_B(*args)

def run_and_verify_All(*args):
    run_command(*args)
    if not verify_A(*args):
        verify_B(*args)

what I want is:

def run_command(*args)
    runs the commands on linux terminal, no checking


verify_list=['verify_A','verify_B']

def run_and_verify(verify_list):
     run_command(*args)
     for func in verify_list:
         if eval(func):
             print "verification passed"
             return True
        else:
             print "verification is failed... running next verify method"

but my run_and verify function is not working as expected..

Upvotes: 0

Views: 110

Answers (2)

kylieCatt
kylieCatt

Reputation: 11039

You can put functions in a list:

def foo():
    return something

def bar():
    return stuff

lst = [foo, bar]

for func in lst:
    if func()
        print('passed...')
        break  # or return, however you decide to set it up
    else:
        print('failed...')

Upvotes: 1

Abhijit
Abhijit

Reputation: 63767

Considering all the functions have the same signatures, Create a list of functions and use any to evaluate then in the order specified. The short-circuit property of any essentially helps you to ignore all functions past the one that has a success

Example

verify = [verify_A, verify_B, run_and_verify_A, 
          run_and_verify_B, run_and_verify_Allrun_and_verify_All]


def run_and_verify(verify_list, *args):
     run_command(*args)
     if any(fn(*args) for fn in verify_list):
         print "verification passed"
     else:
         print "verification is failed... running next verify method"

Upvotes: 0

Related Questions