python:在shell上显示经过的时间 [英] python: display elapsed time on shell

查看:52
本文介绍了python:在shell上显示经过的时间的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

当我运行我的 Python 脚本时,有一些函数需要几分钟才能完成,所以我想在 shell 上显示某种计时器,通知用户所用的时间.

When I run my Python script, there is some function that takes up to a few minutes to complete, so I want to display on the shell some kind of timer that informs the user on the time elapsed.

是否已经准备好在 Python 中使用这样的东西?

Is there any such thing already ready to use in Python?

推荐答案

一种简单的方法是在您的 sys.ps1 提示(通常定义 >>> 提示)

One simplistic way is to include a clock in your sys.ps1 prompt (the thing that normally defines the >>> prompt)

来自 sys 的文档.ps1:

如果一个非字符串对象被分配给任一变量,它的 str() 每次解释器准备读取一个新的交互式命令时都会重新计算;这可用于实现动态提示.

If a non-string object is assigned to either variable, its str() is re-evaluated each time the interpreter prepares to read a new interactive command; this can be used to implement a dynamic prompt.

~/.local/usercustomize.py (或更准确地说,在 python -c 'import site; print site.USER_BASE' 显示的任何文件夹中),您可以添加:

In ~/.local/usercustomize.py (or more accurately, in whatever folder python -c 'import site; print site.USER_BASE' displays), you can add:

import sys
import datetime


class ClockPS1(object):
  def __repr__(self):
    now = datetime.datetime.now()
    return str(now.strftime("%H:%M:%S >>> "))


sys.ps1 = ClockPS1()

然后您的提示将如下所示:

Then your prompt will look like this:

16:26:24 >>> import time
16:26:27 >>> time.sleep(10)
16:26:40 >>> 

这并不完美,因为最后一次是出现提示的时间,而不是执行该行的时间,但它可能会有所帮助.您可以轻松地显示 __repr__ 调用之间的时间(以秒为单位),并在提示中显示.

It's not perfect, as the last time will be when the prompt appeared, not when the line was executed, but it might be of help. You could easily make this display the time in seconds between __repr__ invokations, and show that in the prompt.

这篇关于python:在shell上显示经过的时间的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆