2016-08-08 2 views
2

파이썬에서 스레드가 잠자기 할 때 인터럽트 할 수있는 방법이 있습니까? (우리가 자바에서 할 수있는 것처럼)파이썬 스레드 인터럽트 잠

나는 그런 것을 찾고있다.

import threading 
    from time import sleep 

    def f(): 
     print('started') 
    try: 
     sleep(100) 
     print('finished') 
    except SleepInterruptedException: 
     print('interrupted') 

t = threading.Thread(target=f) 
t.start() 

if input() == 'stop': 
    t.interrupt() 

스레드 100 초 동안 자고 나는 '정지'를 입력하면, 얼마나 조건 개체를 사용하는 방법에 대한

+1

[Event] (https://docs.python.org/3.5/library/threading.html#threading.Event)를 구현하고 'Event.wait (100)' –

+0

Loop through 100' 시간을 사용할 수 있습니다. sleep (1)'및 예외가 있는지 확인하십시오. –

+0

@Kristof thanks – PolyProgrammist

답변

3

올바른 방법은 threading.Event입니다. 예 :

import threading 

e = threading.Event() 
e.wait(timeout=100) # instead of time.sleep(100) 

e에 액세스해야합니다.

e.set() 

이렇게하면 잠자기가 즉시 중단됩니다. e.wait의 리턴 값을 점검하여 시간이 초과되었거나 인터럽트되었는지 판별 할 수 있습니다. 자세한 내용은 https://docs.python.org/3/library/threading.html#event-objects 설명서를 참조하십시오.