Ipython自定义提示以显示cell run tim

2024-09-30 04:26:32 发布

您现在位置:Python中文网/ 问答频道 /正文

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

我该怎么做?在


Tags: https命令combashipython时间shellzsh
2条回答

有兴趣者请参考在Github上打开的这一期。在

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

这是一个代码片段,它计算每个语句的时间,并在下一个提示之前正确调整后打印出来,还可以通过名称“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()

要在in提示符上方打印,请删除打印,然后在ipython中打印_配置.py设置:

^{pr2}$

或者在同一个文件里(启动.py)使用

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

相关问题 更多 >

    热门问题