如何在IPython 5提示符中包含主机名?

如何在IPython 5提示符中包含主机名?,python,ipython,Python,Ipython,在以前版本的IPython中,通过在配置中包含以下内容,可以很容易地在提示符中包含主机名: c.PromptManager.in_template = '(\H) In [\\#]: ' from IPython.terminal.prompts import Prompts, Token import socket class MyPrompt(Prompts): def __init__(self, *args, **kwargs): hn = socket.ge

在以前版本的IPython中,通过在配置中包含以下内容,可以很容易地在提示符中包含主机名:

c.PromptManager.in_template = '(\H) In [\\#]: '
from IPython.terminal.prompts import Prompts, Token
import socket

class MyPrompt(Prompts):
    def __init__(self, *args, **kwargs):
        hn = socket.gethostname()
        self._in_txt = '({}) In ['.format(hn)
        self._out_txt = '({}) Out['.format(hn)
        super(MyPrompt, self).__init__(*args, **kwargs)

    def in_prompt_tokens(self, cli=None):
        return [
            (Token.Prompt, self._in_txt),
            (Token.PromptNum, str(self.shell.execution_count)),
            (Token.Prompt, ']: '),
        ]

    def out_prompt_tokens(self):
        return [
            (Token.OutPrompt, self._out_txt),
            (Token.OutPromptNum, str(self.shell.execution_count)),
            (Token.OutPrompt, ']: '),
        ]
(将用主机名替换
\H

但是,
PromptManager
config已在IPython 5中删除。当我尝试使用它时,我看到以下警告:

/env/lib/python2.7/site-packages/IPython/core/interactiveshell.py:448: UserWarning: As of IPython 5.0 `PromptManager` config will have no effect and has been replaced by TerminalInteractiveShell.prompts_class
  warn('As of IPython 5.0 `PromptManager` config will have no effect'

那么如何使用IPython 5实现类似的效果呢?

正如警告所示,您应该使用新的
TerminalInteractiveShell.prompts\u class
。因此,要在提示符中包含主机名,可以在配置中删除以下内容:

c.PromptManager.in_template = '(\H) In [\\#]: '
from IPython.terminal.prompts import Prompts, Token
import socket

class MyPrompt(Prompts):
    def __init__(self, *args, **kwargs):
        hn = socket.gethostname()
        self._in_txt = '({}) In ['.format(hn)
        self._out_txt = '({}) Out['.format(hn)
        super(MyPrompt, self).__init__(*args, **kwargs)

    def in_prompt_tokens(self, cli=None):
        return [
            (Token.Prompt, self._in_txt),
            (Token.PromptNum, str(self.shell.execution_count)),
            (Token.Prompt, ']: '),
        ]

    def out_prompt_tokens(self):
        return [
            (Token.OutPrompt, self._out_txt),
            (Token.OutPromptNum, str(self.shell.execution_count)),
            (Token.OutPrompt, ']: '),
        ]
结果显示以下提示:

(marv) In [1]: 'hello, world'
(marv) Out[1]: 'hello, world'

定制提示上的文档:@thomask,该文档说
ip=get_ipython();ip.prompts=MyPrompt(ip)
。应该在
~/.ipython/profile\u default/ipython\u config.py
中的什么位置?还是我的配置文件有误?这是启动文件中的。您还可以在配置文件中通过将
c.TerminalInteractiveShell.prompts\u class
设置为类或其可导入名称的字符串来完成此操作。