我正在使用一种名为 https://github.com/rkern/line_profiler要使用它,您需要在脚本中的多个位置放置一个装饰器,以指示应分析哪些功能。然后通过以下方式执行脚本@profilekernprof -l script_to_profile.py显然,当通过 运行脚本本身时,装饰器未定义,因此脚本崩溃。python script_to_profile.py我知道如何定义标识修饰器,我可以从命令行传递一个标志,并根据标志的设置方式在主脚本中定义它。但是,我不知道如何将装饰器定义(或标志)传递给我加载的模块,以便它们在加载时不会崩溃。有什么想法吗?def profile(func):
return func
1 回答

沧海一幻觉
TA贡献1824条经验 获得超5个赞
一种非常简单的方法是检查是否有名为名称的东西存在,如果不存在,则将其定义为您的身份装饰器。像这样的东西。profile
try:
profile
except NameError:
def profile(func):
return func
你可以走得更远一点,确保它是可调用的 —— 可能不是必需的:
import typing
try:
profile
except NameError:
profile = None
if not isinstance(profile, typing.Callable):
def profile(func):
return func
添加回答
举报
0/150
提交
取消