[英]How to make an optional decorator in Python
我有一组python脚本,我想用kernprof https://github.com/rkern/line_profiler进行分析,但我也希望能够在没有kernprof的正常执行期间运行它。
在没有kernprof的情况下执行期间忽略未定义的@profile的优雅方法是什么? 或任何其他装饰。
示例代码:
@profile
def hello():
print('Testing')
hello()
运行:
kernprof -l test.py
在@profile方法上正确执行探查器
运行:
python test.py
返回错误:
Traceback (most recent call last):
File "test.py", line 1, in <module>
@profile
NameError: name 'profile' is not defined
希望避免在任何地方捕获此错误,因为我希望代码执行,好像@profile是一个no-op,而不是用kernprof调用它。
谢谢! -Laura
编辑:我最终使用cProfile与kcachegrind完全避免装饰器。
python -m cProfile -o profile_data.pyprof run_cli.py
pyprof2calltree -i profile_data.pyprof && qcachegrind profile_data.pyprof.log
如果没有从kernprof执行,则定义一个no-op装饰器:
if 'profile' not in globals():
def profile(func):
return func
Daniel提出的方法的变体是使用以下单行,然后根据您的分析需要对其进行注释和注释:
# Optional no-op decorator, comment when you want to profile
def profile(func): return func
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.