对不起,初学者的问题,但我无法弄清楚 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 时,如果该文件是由 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()')
这会更改您的脚本。导入后,其成员函数、类等可以正常使用。从命令行运行时,它会分析自身。
这是你要找的吗?
从我收集的评论中可能需要更多,所以这里是:
如果您从 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/