目前我的python代码通常如下所示:
...
if not dry_run:
result = shutil.copyfile(...)
else:
print " DRY-RUN: shutil.copyfile(...) "
...
Run Code Online (Sandbox Code Playgroud)
我现在考虑写一些像干跑者的方法:
def dry_runner(cmd, dry_run, message, before="", after=""):
if dry_run:
print before + "DRY-RUN: " + message + after
# return execute(cmd)
Run Code Online (Sandbox Code Playgroud)
但是首先执行cmd,然后将结果提供给dry_runner方法.
我如何用pythonic方式编写这样的方法?
您可以使用这个通用包装函数:
def execute(func, *args):
print 'before', func
if not dry:
func(*args)
print 'after', func
>>> execute(shutil.copyfile, 'src', 'dst')
Run Code Online (Sandbox Code Playgroud)