无法弄清楚如何在程序内部调用 cProfile
很抱歉初学者的问题,但我无法弄清楚 cProfile (我对 Python 真的很陌生)
我可以通过我的终端运行它:
python -m cProfile myscript.py
但我需要在网络服务器上运行它,所以我想把它将查看的脚本中的命令。我该怎么做?我见过使用诸如 __init__ 和 __main__ 之类的术语的东西,但我不太明白它们是什么。
我知道这很简单,我只是仍在努力学习一切,而且我知道有人会知道这一点。
提前致谢!我很感激。
Sorry for the beginner question, but I can't figure out cProfile (I'm really new to Python)
I can run it via my terminal with:
python -m cProfile myscript.py
But I need to run it on a webserver, so I'd like to put the command within the script it will look at. How would I do this? I've seen stuff using terms like __init__ and __main__
but I dont really understand what those are.
I know this is simple, I'm just still trying to learn everything and I know there's someone who will know this.
Thanks in advance! I appreciate it.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
我认为您已经看到过这样的想法:
当您在脚本上调用 python 时,会发生什么情况,该文件的属性
__name__
设置为"__main__"
如果它是该文件由 python 可执行文件直接调用。否则,(如果没有直接调用)它将被导入。现在,如果需要,您可以在脚本上使用此技巧,例如,假设您有:
这会更改您的脚本。导入后,其成员函数、类等可以正常使用。当从命令行运行时,它会分析自身。
这是您要找的吗?
从我收集的评论来看,可能需要更多信息,所以这里是:
如果您正在运行来自 CGI 更改的脚本,它的形式是:
当我说抽象出来时,您可以这样做:
将该文件放在您的 python 上小路。当运行自身时,它将分析您想要分析的函数。
现在,为您的 CGI 脚本创建一个脚本,该脚本执行以下操作:
因此您的 CGI 脚本只是成为您的函数的一个小包装器(无论如何),并且您的函数现在正在自我测试。
然后,您可以使用桌面上的虚构值来分析该函数,远离生产服务器。
可能有更巧妙的方法来实现这一目标,但它会起作用。
I think you've been seeing ideas like this:
What happens is when you call python on a script, that file has an attribute
__name__
set to"__main__"
if it is the file being directly called by the python executable. Otherwise, (if it is not directly called) it is imported.Now, you can use this trick on your scripts if you need to, for example, assuming you have:
This changes your script. When imported, its member functions, classes etc can be used as normal. When run from the command-line, it profiles itself.
Is this what you're looking for?
From the comments I've gathered more is perhaps needed, so here goes:
If you're running a script from CGI changes are it is of the form:
When I say abstract out, you can do this:
Put that file on your python path. When run itself, it will profile the function you want profiling.
Now, for your CGI script, create a script that does:
So your cgi script just becomes a little wrapper for your function (which it is anyway) and your function is now self-testing.
You can then profile the function using made up values on your desktop, away from the production server.
There are probably neater ways to achieve this, but it would work.