James Adams
James Adams

Reputation: 8727

kernprof.py: NameError: name 'profile' is not defined

I get the following error when I run my code which has been annotated with @profile:

Wrote profile results to monthly_spi_gamma.py.prof
Traceback (most recent call last):
  File "/home/james.adams/anaconda2/lib/python2.7/site-packages/kernprof.py", line 233, in <module>
    sys.exit(main(sys.argv))
  File "/home/james.adams/anaconda2/lib/python2.7/site-packages/kernprof.py", line 223, in main
    prof.runctx('execfile_(%r, globals())' % (script_file,), ns, ns)
  File "/home/james.adams/anaconda2/lib/python2.7/cProfile.py", line 140, in runctx
    exec cmd in globals, locals
  File "<string>", line 1, in <module>
  File "monthly_spi_gamma.py", line 1, in <module>
    import indices
  File "indices.py", line 14, in <module>
    @profile
NameError: name 'profile' is not defined

Can anyone comment as to what may solve the problem? I am using Python 2.7 (Anaconda) on Windows 7.

Upvotes: 2

Views: 2829

Answers (2)

shreyas
shreyas

Reputation: 63

kernprof -l -b web_app.py

This worked for me, if we see

kernprof --help

we see an option to include in builtin namespace

usage: kernprof [-h] [-V] [-l] [-b] [-o OUTFILE] [-s SETUP] [-v] [-u UNIT]
                [-z]
                script ...

Run and profile a python script.

positional arguments:
  script                The python script file to run
  args                  Optional script arguments

optional arguments:
  -h, --help            show this help message and exit
  -V, --version         show program's version number and exit
  -l, --line-by-line    Use the line-by-line profiler instead of cProfile.
                        Implies --builtin.
  -b, --builtin         Put 'profile' in the builtins. Use
                        'profile.enable()'/'.disable()', '@profile' to
                        decorate functions, or 'with profile:' to profile a
                        section of code.
  -o OUTFILE, --outfile OUTFILE
                        Save stats to <outfile> (default: 'scriptname.lprof'
                        with --line-by-line, 'scriptname.prof' without)
  -s SETUP, --setup SETUP
                        Code to execute before the code to profile
  -v, --view            View the results of the profile in addition to saving
                        it
  -u UNIT, --unit UNIT  Output unit (in seconds) in which the timing info is
                        displayed (default: 1e-6)
  -z, --skip-zero       Hide functions which have not been called

Upvotes: 1

James Adams
James Adams

Reputation: 8727

I worked this out by using the -l option, i.e.

$ kernprof.py -l my_code.py

Upvotes: 4

Related Questions