report.py
if __name__ == "__main__":
parser = argparse.ArgumentParser(formatter_class=argparse.ArgumentDefaultsHelpFormatter, description = "CHECK-ACCESS REPORTING.")
parser.add_argument('--input','-i', help='Filepath containing the Active Directory userlist')
parser.add_argument('--timestamp', '-t', nargs='?',const="BLANK", help='filepath with environement varible set')
args, unknownargs = parser.parse_known_args(sys.argv[1:])
timestampchecker(args.timestamp)
#checking the value of cons.DISPLAYRESULT is TRUE
main()
timestampchecker 函数:
def timestampchecker(status):
""" Check if the timestamp is to display or not from command line"""
if status is not None:
cons.DISPLAY_TIME_STAMP = True
此函数检查用户是否设置了-t 参数。如果已设置,我已将一个名为 cons.DISPLAYRESULT 的常量定义为 true。
该函数运行良好,并将常量值变为 True。 但是在 main 函数中我实现了这个装饰器,它没有取真值而是取假
timer.py
def benchmarking(timestaus):
def wrapper(funct):
def timercheck(*args, **kwarg):
if timestaus is True:
starttime=time.time()
funct(*args, **kwarg)
if timestaus is True:
print('Time Taken:',round(time.time()-starttime, 4))
return timercheck
return wrapper
我用上面的装饰器装饰了 report.py 的 main() 方法中的一些方法。例如,这是在 report.py 中使用并用上述装饰器装饰的类
class NotAccountedReport:
def __init__(self, pluginoutputpath):
""" Path where the plugins result are stored need these files"""
self.pluginoutputpath = pluginoutputpath
@benchmarking(cons.DISPLAY_TIME_STAMP)
def makeNotAccountableReport():
#some functionality
here I have passed the constant value to the argument decorator which when tested though before called is converted to True is taking false and thus the decorators not being implemented. Where is the problem cant figure out
最佳答案
您没有发布完整的最小可验证示例,因此可能还有其他内容,但如果您的意思是调用 NotAccountedReport().makeNotAccountableReport()
时您没有得到您的“Time taken"打印出来,这真的不足为奇 - benchmarking
装饰器在定义函数时(导入模块时)应用,远早于 if __name__ == '__main__'
子句被执行,所以那时 cons.DISPLAY_TIME_STAMP
还没有被你的命令行参数更新。
如果您想要运行时标志来激活/停用装饰器的行为,显而易见的解决方案是检查装饰器内的 cons.DISPLAY_TIME_STAMP
而不是将其作为参数传递,即:
def benchmarking(func):
def timercheck(*args, **kwarg):
if cons.DISPLAY_TIME_STAMP:
starttime=time.time()
result = func(*args, **kwarg)
if cons.DISPLAY_TIME_STAMP:
logger.debug('Time Taken: %s',round(time.time()-starttime, 4))
return result
return timercheck
class NotAccountedReport(object):
@benchmarking
def makeNotAccountableReport():
#some functionality
关于python装饰器不从传递的常量中获取值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45189944/