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

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

python -m cProfile myscript.py

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

我知道这很简单,我只是在尝试学习所有内容,我知道有人会知道这一点。

提前致谢!我很感激。

有帮助吗?

解决方案

我认为您一直在看到这样的想法:

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

发生的事情是,当您在脚本上调用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()')

这更改了您的脚本。导入时,其成员功能,类等可以正常使用。什么时候 从命令行中,它本身要介绍。

这是您想要的吗?


从我收集到更多的评论也许是需要的,所以这里可以:

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

# do some stuff to extract the parameters
# do something with the parameters
# return the response.

当我说抽象时,您可以做到这一点:

def do_something_with_parameters(param1, param2):
    pass

if __name__ = "__main__":
    import cProfile
    cProfile.run('do_something_with_parameters(param1=\'sometestvalue\')')

将该文件放在您的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

因此,您的CGI脚本只会成为您功能的一些包装器(无论如何),并且您的功能现在正在自我测试。

然后,您可以使用台式机上的“距离生产服务器”上的组成值介绍该函数。

可能有更整洁的方法可以实现这一目标,但它会起作用。

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top