我有一些python脚本,它们的行为取决于运行脚本时用户传递的条件。
我们说我有两个lambdas; verbose_print
和math_foo
,我想用来有条件地在我的python脚本中执行某些操作,具体取决于我是否设置了-m
或-v
标记。
from __future__ import print_function # Future-proofing
import argparse #args
verbose_print = lambda x: 0
math_foo = lambda x, y: 0
def main_func(args):
verbose_print("WILL ONLY PRINT WHEN VERBOSE" )
#other main function stuff
conditional_result = math_foo(12,45)
if __name__ == "__main__":
started_at = time.time()
#declare argparse logic separately from main functionality
parser = argparse.ArgumentParser()
parser.add_argument('-v', '--verbose', action='store_true')
parser.add_argument('-m', '--use_math', action='store_true')
args = parser.parse_args()
verbose_print("Began...") # won't print since this will always be lambda x:0
global verbose_print
verbose_print = lambda x: print(x) if args.verbose and not args.quiet else 0
global math_foo
math_foo = lambda x, y: x^(x+y) if args.use_math else y
main_func(args) #run main function
finished_at = time.time()
verbose_print("Finished (Took {} seconds)".format((finished_at-started_at)))
这种方法显然有效,但我很好奇是否有更多的pythonic解决方案。例如,如果我曾想将此文件用作import
但仍想要日志详细事件,我需要在该新文件中重新定义我的lambda。而不是两个lambdas,如果有11个呢?我每次导入时都不想手工设置11个lambdas!
有没有更好的办法处理这种条件行为?我计划使用python进行更多的个人脚本编写,并且我想知道我是否走上了正确的道路。
答案 0 :(得分:2)
当我看到像verbose_print = lambda x: 0
这样的东西时,我诅咒那些试图以这种奇怪的方式解释lambda
的可怕教程。 lambdas是匿名函数,当你不想定义一个命名函数时使用它......但这正是赋值所做的。只需定义打印功能,并在处理args时在主文件中设置verbose
。
verbose = False
def verbose_print(msg):
global verbose
if verbose:
print(msg)
if __name__ == "__main__":
started_at = time.time()
#declare argparse logic separately from main functionality
parser = argparse.ArgumentParser()
parser.add_argument('-v', '--verbose', action='store_true')
parser.add_argument('-m', '--use_math', action='store_true')
args = parser.parse_args()
verbose_print("Began...") # won't print since this will always be lambda x:0
global verbose
verbose = args.verbose and not args.quiet
global math_foo
math_foo = lambda x, y: x^(x+y) if args.use_math else y
main_func(args) #run main function
finished_at = time.time()
verbose_print("Finished (Took {} seconds)".format((finished_at-started_at)))
答案 1 :(得分:1)
如评论中所述,您应该使用日志记录模块
parser.add_argument('-v', '--verbose', action="count", help="verbose level... repeat up to -vvvv.")
...
args.verbose = min(args.verbose,4)
my_logging_logger.setLevel("CRITICAL ERROR WARN INFO DEBUG".split()[args.verbose])
同样如果它是其他东西
some_fn = lambda x:0
data = {"verbose":lambda x:x**2+sqrt(x),"quiet":lambda x:-1}
for k in dir(args): #I think you can do this ... I dont use argparse enough
if k in data:
some_fn = getattr(args,k)
break;