簡體   English   中英

python中的特定線程出口

[英]specific thread exit in python

我正在使用線程創建可中斷對象,當按下特定鍵時,該對象會發送KeyboardInterrupt命令。 在此過程之后,我再次使用msvcrt.getch()函數。 問題是,直到我按下一次按鍵,線程才會退出。 即,倒數計時功能已完成,但線程仍在等待msvcrt.getch()函數的輸入。

我試圖將exit.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"

這不是最美麗的方法,但是它可以工作。

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")

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM