Python Decorators

Decorators take functions as argument and manipulates with having to modify the original function.

Here is a small example of decorators, my base function which is "run_cmd" takes any bash command as argument and executes them using subprocess.Popen which then returns two values "stdout"and "stderr".

What i want to do is with out touching "run_cmd" function i would like to add some checks like say , if "stderr" is None print as "no error" , else print "stdout", something like that.

So i'm writing a decorator function and add all these checks then i decorate my "run_cmd". Let's see how

#!/usr/bin/pythonimport subprocess

def checker(f):
    def inner(a):
        o, e = f(a)
        if e != '':
            print("Output of your command is: "+o)
    return inner

@checkerdef run_cmd(value):
    p = subprocess.Popen(value, shell=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
    out, err = p.communicate()
    return out.strip('\n'), err.strip('\n')

Here if you observe i'm passing a command to "run_cmd", since it's decorated this whole function will be taken as an argument by "checker", but the arguments i pass to "run_cmd" will be passed to "inner" function that is in "checker", So there i'm creating an instance of "run_cmd" assigning the return values to "o" and "e",  Then everything is as usual , write your if conditions blah blah

See the output of above command:

/usr/bin/python /Users/gil/Desktop/
Output of your command is: gil

Process finished with exit code 0

See output of wrong command

/usr/bin/python /Users/gil/Desktop/
/bin/sh: whoamia: command not found

Process finished with exit code 1


Python Decorators Python Decorators Reviewed by shiva on 4/05/2016 Rating: 5

No comments:

Powered by Blogger.