954,557 Members — Technology Publication meets Social Media
Username:
Password:
Lost login information?
Have something to say? Contribute New Article Reply to this Article

Interrupt Sleep function

Is there a way one can interrupt the sleep() function with a key press in Python?

bumsfeld
Nearly a Posting Virtuoso
1,445 posts since Jul 2005
Reputation Points: 404
Solved Threads: 184
 

Look at KeyboardInterrupt in the Python reference. Right now, I don't have a good example. I try to work on one!

vegaseat
DaniWeb's Hypocrite
Moderator
5,989 posts since Oct 2004
Reputation Points: 1,345
Solved Threads: 1,417
 

So far I have only found one function that will work during the active sleep() ...

import time
import msvcrt
time.sleep(10)
# prints the key value during sleep
if msvcrt.kbhit():
    print msvcrt.getch()

Edit:
Ouch! The IDE fooled me! This does not make sense, forget it! Sorry!

vegaseat
DaniWeb's Hypocrite
Moderator
5,989 posts since Oct 2004
Reputation Points: 1,345
Solved Threads: 1,417
 

If it's anything like the sleep(t) function I have been using with C++, there is no way to stop it early. Maybe ctrl/alt/del, but that is not what you want to normally do.

Ene Uran
Posting Virtuoso
1,723 posts since Aug 2005
Reputation Points: 625
Solved Threads: 213
 

havn't got an example, but my very rough guess is maybe you could do something along the lines of;

wrap a function around the time.sleep() function that when called it starts the sleep in another thread so that the program will only continue untill;
sleep ends,
thread gets killed (stoppped)
so the way to interrupt could be to manually shut down the thread which in turn would shut down the sleep

OR

you could make your own sleep class that allows you to kill it?

something along those lines anyway
not too experienced on threading or using classes

a1eio
Junior Poster
141 posts since Aug 2005
Reputation Points: 26
Solved Threads: 25
 

Thanks a1eio,
I just remembered hanging an old Delphi snippet on the DaniWeb code snippet laundry line a long time ago, that talked about the very same thing that Ene brought up.

vegaseat
DaniWeb's Hypocrite
Moderator
5,989 posts since Oct 2004
Reputation Points: 1,345
Solved Threads: 1,417
 

no probs, glad i could help :)

*edit: that smiley looks evil

a1eio
Junior Poster
141 posts since Aug 2005
Reputation Points: 26
Solved Threads: 25
 

This question has already been solved

Post: Markdown Syntax: Formatting Help
You