error:

line 10
    %matplotlib inline
    ^
SyntaxError: invalid syntax.

solution:

魔法行仅由IPython命令行支持。它们不能简单地在脚本中使用,因为Python语法中有些地方不正确。

如果希望从脚本执行此操作,则必须访问IPython API,然后调用run_line_magic函数。

  • Line magics are only supported by the IPython command line. They cannot simply be used inside a script, because %something is not correct Python syntax.

  • If you want to do this from a script you have to get access to the IPython API and then call the run_line_magic function.

代替%matplotlib inline,你需要在你的代码中做类似这样的事情:

from IPython import get_ipython
get_ipython().run_line_magic('matplotlib', 'inline')

在这个答案中描述了一种类似的方法,但是它使用了不推荐使用的magic函数。

注意,该脚本仍然需要在IPython中运行。在普通Python中,get_ipython函数返回None,而get_ipython().run_line_magic将引发一个AttributeError错误。

  • A similar approach is described in this answer, but it uses the deprecated magic function.

  • Note that the script still needs to run in IPython. Under vanilla Python the get_ipython function returns None and get_ipython().run_line_magic will raise an AttributeError.