python模块导入问题

时间:2010-12-01 20:18:22

标签: python module profiling

所以我有一个包含许多模块的大项目,我想对它进行一些分析。我有一个配置文件模块,基本上只提供一个装饰器,我可以添加到一个函数,以便在调用它时对其进行分析。

问题是,我必须将该模块导入到我拥有的几十个模块中。我猜这很好,但我无法将导入的分析模块或函数上的装饰器推送到版本控制。这意味着每次导入/导出时,我都必须添加/删除所有的分析代码。

是否有任何类型的系统来管理这种添加/删除分析代码而无需手动导入/删除项目的每个模块中的模块?我们使用mercurial,但我不能真正搞乱mercurial设置或分支。

2 个答案:

答案 0 :(得分:2)

您可以创建分析模块,以便导入其他模块并注释其功能:

# these are the modules you want to profile
import foo
import huh

# This is a profiling function
# yours would do something smarter
def profile(f):
    def gotcha(*args, **kwds):
        print "before"
        result = f(*args, **kwds)
        print "after"
        return result
    return gotcha

# these are the functions in those modules that you
# want to profile.  Each one is patched here instead
# of decorated there.
foo.bar = profile(foo.bar)
huh.baz = profile(huh.baz)
huh.hmm = profile(huh.hmm)

这样您就不必修改这些模块,但是如果您选择在运行时将该分析模块导入任何位置,它将根据您的需要“修补”所有其他模块

你应该能够类似地装饰类方法。

答案 1 :(得分:0)

为什么不只是创建一个包含所有性能分析更改的分支,然后在想要测试时合并分支...并在之后恢复所有内容。

使用它的“git stash”,git使这更容易一些,但使用分支不应该更难。

相关问题