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.

asked Feb 5, 2015 at 1:14

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.

Adam Smith
54.5k13 gold badges84 silver badges120 bronze badges
answered Feb 5, 2015 at 1:17
2
  • I removed your disclaimer since it's not really important to answer the question. It might be better as a comment on the question. Commented Feb 6, 2015 at 0:25
  • @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. Commented Feb 6, 2015 at 1:12

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

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.