Delay a computation in another thread

Steve D'Aprano steve+python at pearwood.info
Sat Sep 2 06:53:27 EDT 2017


I want to delay a computation and then print it, in the REPL (interactive
interpreter). I have something like this:


import time
from threading import Timer

def do_work():
    x = 2 + 2
    print("It is", time.asctime(), "and 2+2 is", x)

def schedule_work():
    Timer(60, do_work, ()).start()  # schedule it in one minute


Is this the right way to do it?

If I do that, it works, mostly. For example:

py> schedule_work()
py> dir(45)  # do other stuff, in the interactive interpreter, for one minute
['bit_length', 'conjugate', 'denominator', 'from_bytes', 'imag', 'numerator', 'real', 'to_bytes']
py>
py> It is Sat Sep  2 20:37:58 2017 and 2+2 is 4


The problem is that after the message is printed, the REPL's prompt is
disrupted. This is especially annoying when I'm in the middle of typing a line.
This is just a cosmetic flaw, but it would be nice if I could tell Python to
redraw the current line. For example, using _ to indicate the position of the
cursor, this is what happens now:

py> class K:
...     attribute =It is Sat Sep  2 20:48:39 2017 and 2+2 is 4
_


This is what I'd prefer:

py> class K:
...     attribute =It is Sat Sep  2 20:48:39 2017 and 2+2 is 4
...     attribute =_


The other problem is that if I exit the REPL while a Timer is still active, it
freezes until the time has run before exiting. I know you can't kill a thread
from the main thread, but is there a way for the Timer to see that the
interpreter is shutting down and shut itself down?



-- 
Steve
“Cheer up,” they said, “things could be worse.” So I cheered up, and sure
enough, things got worse.




More information about the Python-list mailing list