Ipython customize prompt to display cell run time

爷,独闯天下 提交于 2020-02-04 05:54:52

问题


i am wondering how to configure Ipython so that it adds the run time of the last command in milliseconds/seconds to the right command prompt. This could be done in ZSH/Bash shells as illustrated here https://coderwall.com/p/kmchbw

How should I go about doing this?


回答1:


This is a code snippet that times each statement and prints it right adjusted before the next prompt, and also makes the value accessible by name '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()

To print it above the in-prompt instead, remove the print, and in ipython_config.py set:

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

or in the same file (startup.py) use

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



回答2:


For those who are interested, please refer to this issue opened in Github.

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



来源:https://stackoverflow.com/questions/22150661/ipython-customize-prompt-to-display-cell-run-time

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!