Ipython自定义提示以显示单元运行时

时间:2014-03-03 15:27:29

标签: python ipython

我想知道如何配置Ipython,以便将最后一个命令的运行时间(以毫秒/秒为单位)添加到正确的命令提示符。这可以在ZSH / Bash shell中完成,如https://coderwall.com/p/kmchbw

所示

我该怎么做呢?

2 个答案:

答案 0 :(得分:1)

对于有兴趣的人,请参阅Github中打开的这个问题。

https://github.com/ipython/ipython/issues/5237

答案 1 :(得分:1)

这是一个代码段,用于对每个语句进行计时,并在下一个提示之前对其进行正确调整,并且还可以通过名称' texc'来访问该值。

# Assumes from __future__ import print_function
from time import time
import blessings  # Not a necessary requirement
class ExecTimer(object):
    def __init__(self, ip):
        self.shell = ip
        self.t_pre = time()
        self.texc = 0
        self.prev_texc = 0
        self.term = blessings.Terminal()

    def pre_execute(self):
        self.t_pre = time()

    def post_execute(self):
        self.prev_texc = self.texc
        self.texc = round(time() - self.t_pre, 4)
        print(self.term.bold_blue(
            '{} s'.format(self.texc).rjust(self.term.width - 1)
        ))
        # Only add or update user namespace var if it is safe to do so
        if 'texc' not in self.shell.user_ns or \
                self.shell.user_ns['texc'] == self.prev_texc:
            self.shell.push({'texc': self.texc})
        else:
            pass

    def register(self):
        self.shell.events.register('pre_execute', self.pre_execute)
        self.shell.events.register('post_execute', self.post_execute)

ExecTimer(get_ipython()).register()

要在输入提示上方打印它,请删除打印,并在ipython_config.py中设置:

c.PromptManager.in_template = '{texc} s\nIn[\\#]: '

或在同一个文件(startup.py)中使用

get_ipython().run_line_magic(
    'config',
    r"PromptManager.in_template = '{texc} s\nIn[\\#]: '"
)