对不起初学者的问题,但我不知道 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 脚本只是成为你的函数的一个小包装器(无论如何它都是),你的函数现在是自测试的。
然后,您可以在远离生产服务器的桌面上使用组成的值来分析函数。
可能有更简洁的方法来实现这一点,但它会起作用。