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

2 投票
2 回答
731 浏览
提问于 2025-04-17 20:38

我想知道怎么设置Ipython,让它在右边的命令提示符上显示上一个命令的运行时间,单位是毫秒或秒。这个功能在ZSH/Bash的命令行中可以实现,具体可以参考这里 https://coderwall.com/p/kmchbw

我该怎么做呢?

2 个回答

1

如果你感兴趣,可以看看在Github上开这个问题的讨论。

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

2

这是一个代码片段,它会记录每条语句的执行时间,并在下一个提示符之前把时间右对齐打印出来,同时也可以通过名字'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[\\#]: '"
)

撰写回答