目前,我的python代码通常如下所示:
...
if not dry_run:
result = shutil.copyfile(...)
else:
print " DRY-RUN: shutil.copyfile(...) "
...我现在考虑写一些类似于干跑道方法的东西:
def dry_runner(cmd, dry_run, message, before="", after=""):
if dry_run:
print before + "DRY-RUN: " + message + after
# return execute(cmd)但cmd将首先执行,并将结果提供给dry_runner方法。
我如何才能以pythonic方式编写这样的方法呢?
发布于 2010-07-19 19:30:18
你可以使用这个通用的包装器函数:
def execute(func, *args):
print 'before', func
if not dry:
func(*args)
print 'after', func
>>> execute(shutil.copyfile, 'src', 'dst')发布于 2011-03-16 22:55:05
这在显示上并不完美,但其功能是有效的。希望这一点足够清楚:
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')https://stackoverflow.com/questions/3279806
复制相似问题