【问题标题】:invalid syntax when run cProfile运行 cProfile 时语法无效
【发布时间】:2015-08-06 16:47:44
【问题描述】:

我尝试运行python -m cProfile simple_test_script.py。我使用的是 Windows 7,Python 2.7.10。

simple_test_script.py:

import numpy as np
from numpy.linalg import eigvals

def run_experiment(niter=100):
    K = 100
    results = []
    for _ in xrange(niter):
        mat = np.random.randn(K, K)
        max_eigenvalue = np.abs(eigvals(mat)).max()
        results.append(max_eigenvalue)
    return results
some_results = run_experiment()
print 'Largest one we saw: %s' % np.max(some_results)

我收到此错误:

File "<ipython-input-13-6634cb53f497>", line 1
    python -m cProfile simple_test_script.py
                     ^
SyntaxError: invalid syntax

我阅读了这份文档:https://docs.python.org/2/library/profile.html

(如果 cProfile 不可用,则使用 profile 而不是 cProfile 你的系统。)

我尝试使用 profile 而不是 cProfile 但同样的错误。有什么线索可以调用 cProfile 吗?

【问题讨论】:

    标签: python ipython profile cprofile


    【解决方案1】:

    您似乎在 IPython 中运行以下命令:

    python -m cProfile simple_test_script.py
    

    你应该在你的 shell 中运行它。

    【讨论】:

    • 谢谢@satoru!我想在 IPython 中运行它。但感谢您很好地解释了为什么会出现错误。
    【解决方案2】:

    正如 satoru 建议的那样,您通常会在 shell/终端/控制台中运行这样的命令(对于日常使用,这些基本上意味着相同的东西)。但是,您也可以从 IPython 内部运行它,例如:

    %run -m cProfile simple_test_script.py
    

    (% 符号是命令的一部分,IPython 有一些以 % 开头的特殊命令)

    【讨论】:

    • 谢谢!那效果很好。 %run -m cProfile simple_test_script.py
    猜你喜欢
    • 2019-01-11
    • 2015-06-20
    • 1970-01-01
    • 2023-03-04
    • 2022-08-16
    • 2019-01-25
    • 2021-01-26
    • 2012-07-03
    • 1970-01-01
    相关资源
    最近更新 更多