파이썬은 차단 스레드를 종료합니까?
-
23-08-2019 - |
문제
내 코드에서 나는 루프입니다 raw_input()
사용자가 종료를 요청했는지 확인합니다. 사용자가 종료하기 전에 내 앱이 종료 될 수 있지만, 차단 기능에서 돌아올 키를 입력 할 때까지 앱이 여전히 살아 있다는 것입니다. raw_input()
. 강제로 할 수 있습니까? raw_input()
가짜 입력을 보내서 돌아와서? 켜져있는 스레드를 종료 할 수 있습니까? (유일한 데이터는 단일 변수입니다. wantQuit
).
해결책
기능을 감싸는이 타임 아웃 기능을 사용할 수 있습니다. 다음은 다음과 같습니다. http://code.activestate.com/recipes/473878/
def timeout(func, args=(), kwargs={}, timeout_duration=1, default=None):
'''This function will spwan a thread and run the given function using the args, kwargs and
return the given default value if the timeout_duration is exceeded
'''
import threading
class InterruptableThread(threading.Thread):
def __init__(self):
threading.Thread.__init__(self)
self.result = default
def run(self):
try:
self.result = func(*args, **kwargs)
except:
self.result = default
it = InterruptableThread()
it.start()
it.join(timeout_duration)
if it.isAlive():
return it.result
else:
return it.result
다른 팁
스레드를 데모닉으로 표시하지 않는 이유는 무엇입니까?
로부터 문서:
스레드는 "데몬 스레드"로 표시 될 수 있습니다. 이 플래그의 중요성은 데몬 스레드 만 남을 때 전체 파이썬 프로그램이 종료된다는 것입니다. 초기 값은 생성 스레드에서 상속됩니다. 플래그는 데몬 속성을 통해 설정할 수 있습니다.
비 블로킹 함수를 사용하여 사용자 입력을 읽을 수 있습니다.
이 솔루션은 Windows 특정입니다.
import msvcrt
import time
while True:
# test if there are keypresses in the input buffer
while msvcrt.kbhit():
# read a character
print msvcrt.getch()
# no keypresses, sleep for a while...
time.sleep(1)
UNIX에서 비슷한 일을하려면 char의 Windows 버전 읽기 Char와 달리 (Python 사용자 포럼에 대한 링크를 제공 한 Aaron Digulla 덕분) :
import sys
import select
i = 0
while i < 10:
i = i + 1
r,w,x = select.select([sys.stdin.fileno()],[],[],2)
if len(r) != 0:
print sys.stdin.readline()
이있다 파이썬 메일 링리스트에 게시하십시오 UNIX를 위해이 작업을 수행하는 방법을 설명합니다.
# this works on some platforms:
import signal, sys
def alarm_handler(*args):
raise Exception("timeout")
def function_xyz(prompt, timeout):
signal.signal(signal.SIGALRM, alarm_handler)
signal.alarm(timeout)
sys.stdout.write(prompt)
sys.stdout.flush()
try:
text = sys.stdin.readline()
except:
text = ""
signal.alarm(0)
return text
제휴하지 않습니다 StackOverflow