对于初学者的问题很抱歉,但我无法弄清楚 cProfile(我真的是 Python 的新手)
我可以通过我的终端运行它:
python -m cProfile myscript.py
但我需要在网络服务器上运行它,所以我想将命令放在它要查看的脚本中。我该怎么做?我见过使用 __init__ 和 __main__
等术语的东西,但我真的不明白它们是什么。
我知道这很简单,我仍在努力学习一切,我知道有人会知道这一点。
提前致谢!我很感激。
最佳答案
我认为您已经看到了这样的想法:
if __name__ == "__main__":
# do something if this script is invoked
# as python scriptname. Otherwise, gets ignored.
当您在脚本上调用 python 时,如果该文件是 python 直接调用的文件,则该文件的属性 __name__
设置为 "__main__"
可执行。否则,(如果不是直接调用)它被导入。
现在,如果需要,您可以在脚本中使用这个技巧,例如,假设您有:
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()')
这会改变您的脚本。导入后,其成员函数、类等可以正常使用。当从命令行运行时,它会 self 分析。
这是您要找的吗?
从我收集到的评论中可能还需要更多,所以这里是:
如果您从 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 脚本只是变成了你的函数的一个小包装器(不管怎样),你的函数现在是自测试的。
然后,您可以在远离生产服务器的桌面上使用虚构的值来分析函数。
可能有更简洁的方法来实现这一点,但它会起作用。
关于python - 无法弄清楚如何在程序内部调用 cProfile,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3489769/