开发者

Method for dry runs?

开发者 https://www.devze.com 2023-01-08 09:15 出处:网络
at the moment my python code often looks like this: ... if not dry_run: result = shutil.copyfile(...) else:

at the moment my python code often looks like this:

...
if not dry_run:
    result = shutil.copyfile(...)
else:
    print "   DRY-RUN: shutil.copyfile(...) "
...

I now think about writting something like a dry runner method:

def dry_runner(cmd, dry_run, message, before="", after=""):
    if dry_run:
        print before + "DRY-RUN: " + message + after
     # return execute(cmd)

But 开发者_运维问答the cmd will be executed first and the result is given to dry_runner method.

How can I code such a method the pythonic way?


You could use this generic wrapper function:

def execute(func, *args):
    print 'before', func
    if not dry:
        func(*args)
    print 'after', func

>>> execute(shutil.copyfile, 'src', 'dst')


This isn't perfect in its display, but the functionality works. Hopefully this is clear enough:

dry = True

def dryrun(f):
    def wrapper(*args, **kwargs):
        if dry:
            print "DRY RUN: %s(%s)" % (f.__name__, 
                                       ','.join(list(args) + ["%s=%s" % (k, v) for (k, v) in kwargs.iteritems()])) 
        else:
            f(*args, **kwargs)
    return wrapper

import shutil
copyfile = dryrun(shutil.copyfile)

copyfile('a', 'b')
0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号