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.

Community
  • 1
  • 1
Dave Kielpinski
  • 1,152
  • 1
  • 9
  • 20

1 Answers1

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
  • 52,157
  • 12
  • 73
  • 112
Dave Kielpinski
  • 1,152
  • 1
  • 9
  • 20
  • I removed your disclaimer since it's not really important to answer the question. It might be better as a comment on the question. – Adam Smith Feb 06 '15 at 00: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. – Dave Kielpinski Feb 06 '15 at 01:12