Alex Luk
Alex Luk

Reputation: 41

Problems trying to use cProfile

I am trying to run the code below at Python 2.7 GUI:

python -m cProfile -s time abc.py

However here is the error I have:

>>> python -m cProfile -s time abc.py     
>>>                  ^
>>> SyntaxError: invalid syntax

Any idea how can I solve it?

Upvotes: 1

Views: 1277

Answers (2)

Mike Müller
Mike Müller

Reputation: 85582

You need to run this from the command line, not a GUI or the interactive Python prompt. Seeing the >>> means you are on the interactive Python prompt.

On the command line a.k.a terminal window, change to the directory in which abc.py is located and enter:

python -m cProfile -s time abc.py  

I get this:

python -m cProfile -s time abc.py 
         2 function calls in 0.000 seconds

   Ordered by: internal time

   ncalls  tottime  percall  cumtime  percall filename:lineno(function)
        1    0.000    0.000    0.000    0.000 {method 'disable' of '_lsprof.Profiler' objects}
        1    0.000    0.000    0.000    0.000 abc.py:1(<module>)

The option -m does this:

-m mod : run library module as a script (terminates option list)

The Python version is 2.7.12.

EDIT

If you want to do it from the interactive prompt, probably the easiest way is to use IPython or Jupyter Notebook. Then you can do this:

[1] %run -m cProfile -s time abc.py

Upvotes: 1

jez
jez

Reputation: 15369

python -m ... is not itself Python syntax: it's a syntax for starting Python from outside. Therefore, the Python interpreter (GUI or not) will fail to process that command. (We know you're working from inside the Python interpreter because of the telltale >>> prompt.)

What does "from outside" mean? It means you need to type that command at the > prompt in the Command Window (in Windows) or at the $ prompt in a terminal window running the bash shell (in other likely OSes).

Upvotes: 0

Related Questions