尝试使用 cProfile 的问题

Problems trying to use cProfile

我正在尝试 运行 下面的代码 Python 2.7 GUI:

python -m cProfile -s time abc.py

但是我遇到的错误是:

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

知道我该如何解决吗?

您需要从命令行运行,不是 GUI 或交互式Python 提示。看到 >>> 表示您处于交互式 Python 提示符下。

命令行a.k.a终端window,切换到abc.py所在目录,输入:

python -m cProfile -s time abc.py  

我明白了:

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>)

选项 -m 这样做:

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

Python版本是2.7.12.

编辑

如果您想从交互式提示中进行操作,最简单的方法可能是使用 IPython or Jupyter Notebook。那么你可以这样做:

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

python -m ... 本身不是 Python 语法:它是从外部开始 Python 的语法。因此,Python 解释器(GUI 或非 GUI)将无法处理该命令。 (我们知道您是在 Python 解释器内部工作,因为 >>> 提示符很明显。)

"from outside"是什么意思?这意味着您需要在命令 Window(在 Windows 中)的 > 提示符下或终端 window 中的 $ 提示符下键入该命令 运行 bash shell(在其他可能的操作系统中)。