默认情况下,IPython的默认提示符格式是如下:
$ ipython
Python 3.6.1 (default, Apr 6 2017, 11:37:13)
Type 'copyright', 'credits' or 'license' for more information
IPython 6.2.1 -- An enhanced Interactive Python. Type '?' for help.
In [1]: import numpy as np
In [2]: a = np.arange(15).reshape(3, 5)
In [3]: a
Out[3]:
array([[ 0, 1, 2, 3, 4],
[ 5, 6, 7, 8, 9],
[10, 11, 12, 13, 14]])
是In [1]:
加上行号的格式。输出代码也是同样的格式Out[3]:
。
有的时候我们在写测试代码,希望把它复制到博客里面的时候,这种格式看起来就不那么美观,更希望它是Python的默认提示符>>>
风格。
$ python
Python 3.6.1 (default, Apr 6 2017, 11:37:13)
[GCC 4.2.1 Compatible Apple LLVM 8.1.0 (clang-802.0.38)] on darwin
Type "help", "copyright", "credits" or "license" for more information.
>>> import numpy as np
>>> a = np.arange(15).reshape(3, 5)
>>> a
array([[ 0, 1, 2, 3, 4],
[ 5, 6, 7, 8, 9],
[10, 11, 12, 13, 14]])
那我们该如何配置呢? 具体操作如下(文末更新有最简单的方式):
首先创建IPython的自定义配置文件
$ ipython profile create
[ProfileCreate] Generating default config file: '~/.ipython/profile_default/ipython_config.py'
[ProfileCreate] Generating default config file: '~/.ipython/profile_default/ipython_kernel_config.py'
可以看到在HOME目录下: 多了两个配置文件
我们修改~/.ipython/profile_default/ipython_config.py
文件, 在文件的最底部,
加入如下代码:
$ tail -n 12 ~/.ipython/profile_default/ipython_config.py
from IPython.terminal.prompts import Prompts, Token
import os
class MyPrompt(Prompts):
def in_prompt_tokens(self, cli=None):
return [(Token.Prompt, '>>> ')]
def out_prompt_tokens(self):
return []
c.TerminalInteractiveShell.prompts_class = MyPrompt
重新打开IPython, 实现效果如下:
$ ipython
Python 3.6.1 (default, Apr 6 2017, 11:37:13)
Type 'copyright', 'credits' or 'license' for more information
IPython 6.2.1 -- An enhanced Interactive Python. Type '?' for help.
>>> import numpy as np
>>> a = np.arange(15).reshape(3, 5)
>>> a
array([[ 0, 1, 2, 3, 4],
[ 5, 6, 7, 8, 9],
[10, 11, 12, 13, 14]])
参考:
http://ipython.readthedocs.io/en/stable/config/details.html#custom-prompts
更新
在看了Ipython的代码IPython/terminal/prompts.py
时,发现它已经定义好了经典提示符的风格ClassicPrompts
。不需要我们再自定义实现了,直接在配置文件~/.ipython/profile_default/ipython_config.py
里配置使用它即可
c.TerminalInteractiveShell.prompts_class = 'IPython.terminal.prompts.ClassicPrompts'
网友评论