python: display elapsed time on shell
Question: 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.

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


Answer: One simplistic way is to include a clock in your
[`sys.ps1`](http://docs.python.org/2/library/sys.html?highlight=sys.ps1#sys.ps1)
prompt (the thing that normally defines the `>>>` prompt)

From the documentation for
[`sys.ps1`](http://docs.python.org/2/library/sys.html?highlight=sys.ps1#sys.ps1):

> 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.

In [`~/.local/usercustomize.py`](http://www.doughellmann.com/PyMOTW/site/) (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 >>> 
    

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.

