无法弄清楚如何在程序中调用cProfile

Par*_*ker 2 python time profiler cprofile

对不起初学者的问题,但我无法弄清楚cProfile(我是Python的新手)

我可以通过我的终端运行它:

python -m cProfile myscript.py
Run Code Online (Sandbox Code Playgroud)

但我需要在网络服务器上运行它,所以我想将命令放在它将要查看的脚本中.我该怎么做?我用类似的术语看过东西,__init__ and __main__但我真的不明白那些是什么.

我知道这很简单,我只是想学习一切,我知道有人会知道这一点.

提前致谢!我很感激.

小智 5

我想你一直在看到这样的想法:

if __name__ == "__main__":
    # do something if this script is invoked
    # as python scriptname. Otherwise, gets ignored.
Run Code Online (Sandbox Code Playgroud)

当您在脚本上调用python时,该文件的属性__name__设置为"__main__"如果它是由python可执行文件直接调用的文件.否则,(如果没有直接调用)它将被导入.

现在,如果您需要,可以在脚本上使用此技巧,例如,假设您拥有:

def somescriptfunc():
    # does something
    pass


if __name__ == "__main__":
    # do something if this script is invoked
    # as python scriptname. Otherwise, gets ignored.

    import cProfile
    cProfile.run('somescriptfunc()')
Run Code Online (Sandbox Code Playgroud)

这会改变您的脚本.导入时,其成员函数,类等可以正常使用.当运行在命令行,它本身型材.

这是你在找什么?


从我收集的评论中可能需要更多,所以这里是:

如果您正在从CGI运行脚本,则更改形式如下:

# do some stuff to extract the parameters
# do something with the parameters
# return the response.
Run Code Online (Sandbox Code Playgroud)

当我说抽象出来时,你可以这样做:

def do_something_with_parameters(param1, param2):
    pass

if __name__ = "__main__":
    import cProfile
    cProfile.run('do_something_with_parameters(param1=\'sometestvalue\')')
Run Code Online (Sandbox Code Playgroud)

将该文件放在python路径上.运行时,它将分析您想要分析的功能.

现在,对于您的CGI脚本,创建一个执行以下操作的脚本:

import {insert name of script from above here}

# do something to determine parameter values
# do something with them *via the function*:
do_something_with_parameters(param1=..., param2=...)
# return something
Run Code Online (Sandbox Code Playgroud)

所以你的cgi脚本只是成为你的函数的一个小包装(它无论如何),你的函数现在自我测试.

然后,您可以使用桌面上的组合值来分析功能,远离生产服务器.

可能有更简洁的方法来实现这一点,但它会起作用.