Skip to main content
 首页 » 编程设计

python之Ipython 自定义提示以显示单元格运行时间

2024年11月01日11zengkefu

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

我应该怎么做?

请您参考如下方法:

这是一个代码片段,它对每个语句进行计时并在下一个提示之前正确打印它,并且还使值可以通过名称“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[\\#]: '" 
)