[英]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.