1

I'm profiling a Python 3.4 script within an interactive shell environment (IDE, if it matters). Normally I use cProfile to profile functions. However, this time I have some top-level code in the script. By "top-level" I mean that the code is not inside a function definition. cProfile.run won't accept the filename - normally I would pass it a function.

To get around this, I wrap the top-level code in a main() function, execute it to create main in the shell namespace, then run cProfiler.run('main()'). This is pretty annoying - I would like to fool around with several variables generated in the top-level code, and I'd rather not try to return them all from main().

I have carefully read the similar questions How can you profile a python script? and How to profile my code?. They give great solutions for profiling top-level code from the command line and for profiling functions from a shell, but I don't think they address this specific question.

1 Answer 1

1

I have a kluge for getting this done, but I think there's probably a better way out there.

cProfile.run(compile(open(filename, "rb").read(), filename, 'exec'))

where filename is the filename of the script.

Sign up to request clarification or add additional context in comments.

2 Comments

I removed your disclaimer since it's not really important to answer the question. It might be better as a comment on the question.
@AdamSmith OK, thanks - I haven't ever answered my own question before. Repeated for anyone who cares: since I've answered my own question here, I will not upvote or accept my own answer.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.