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.
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.