0

I am using a thread to create an interruptible, which sends the KeyboardInterrupt command when a specific key is pressed. After this process I again use the msvcrt.getch() function. the problem is that the thread won't exit until I have pressed the key once. Ie the countdown function finishes but the the thread is still waiting for the input for the msvcrt.getch() function.

I tried putting exit.thread() at the end of the countdown function, but that exited the main thread. Do I need to use threading instead of thread?

import time, thread, msvcrt

print "enter time for timer"
n=raw_input()

def input_thread():
    z=msvcrt.getch()
    if z == "a" :   
        thread.interrupt_main()
    if z != "a" :
        thread.start_new_thread(input_thread, ())
        print "nope"
        thread.exit()

def countdown(n):
    try:
        thread.start_new_thread(input_thread, ())
        for i in range(int(n)):
            c = int(n) - int(i)
            print c ,'seconds left','\r',
            time.sleep(1)

    except KeyboardInterrupt:
        print "I was rudly interrupted"

countdown(n)
print """

"""
k=msvcrt.getch()
if k == "k" :
    print "you typed k"
else :
    print "you did not type K"
3
  • stackoverflow.com/questions/2757318/… Commented May 16, 2014 at 22:58
  • Do I need to use threading instead of thread? Yes. threading is the high-level API, thread is low-level. Commented May 16, 2014 at 23:02
  • use t = threading.Thread(target=input_thread) Commented May 16, 2014 at 23:51

1 Answer 1

0

It is not the most beautiful way, but it works.

from concurrent.futures import thread
import threading
import time, msvcrt

print("enter time for timer")
n=input()

def input_thread():
   z=msvcrt.getch()
   if z == "a" :
       thread.interrupt_main()
   if z != "a" :
       thread.start_new_thread(input_thread, ())
       print ("nope")
       thread.exit()

def countdown(n):
try:
    threading.Thread(target=input_thread)
    for i in range(int(n)):
        c = int(n) - int(i)
        print (c ,'seconds left','\r')
        time.sleep(1)

except KeyboardInterrupt:
    print("I was rudly interrupted")

countdown(n)
print ("")
k=msvcrt.getch()
if k == "k" :
    print("you typed k")
else :
    print ("you did not type K")
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.