Python: 이벤트를 모니터링하기 위해 새 스레드를 열어 프로그램 실행 중 키보드 입력 모니터링 실현

이전 기사에서는 Python 프로그램이 Windows 시스템에서 키보드 입력을 모니터링하는 두 가지 방법, 즉 키보드 및 pynput 툴킷을 소개했지만 두 방법 모두 Linux 서버를 원격으로 제어할 때 문제가 발생합니다. Python: Windows 시스템에서 모니터링 키보드 입력의 두 가지
방법

이 글에서는 프로그램 실행 중 키보드 입력 모니터링을 구현하기 위해 새로운 스레드를 열어 이벤트를 모니터링하는 방법을 소개하며, 이 방법은 원격으로 리눅스 서버를 제어할 때도 정상적으로 사용할 수 있다.


먼저 능동적으로 끝을 제어할 수 있는 스레드를 정의하려면 스레딩에서 Thread 클래스를 상속하고 _stop 메서드를 다시 작성해야 합니다.

import threading

class StoppableThread(threading.Thread):
    """
    a stoppable thread, inherit from threading.Thread
    """
    def __init__(self, target):
        super(StoppableThread, self).__init__(target=target)

    def _stop(self):
        """
        stop the thread, overwrite method, modified from threading.py
        :return:
        """

        lock = self._tstate_lock
        self._is_stopped = True
        self._tstate_lock = None
        if not self.daemon:
            with threading._shutdown_locks_lock:
                threading._shutdown_locks.discard(lock)

여기서 Python 버전은 3.7 이상입니다. Python 3.6을 사용하는 경우 스레딩 모듈에 _shutdown_locks_lock 속성이 없다는 오류가 보고됩니다.
파이썬 3.6 오류

이벤트를 정의하고 이벤트에 따라 스레드의 대상 함수를 작성합니다.

# event
event_flag = threading.Event()
event_flag.set()

def thread_target():
    """
    thread target function, inspect event flag
    :return:
    """

    global event_flag

    while True:
        if event_flag.is_set():
            input("Press <enter> to pause:")
            event_flag.clear()
        event_flag.wait()

효과를 확인하기 위해 메인 스레드는 for 루프를 통해 시간이 초과되고 새 스레드는 키보드 입력을 모니터링합니다.

import time

if __name__ == '__main__':
    # thread
    thread = StoppableThread(target=thread_target)
    thread.start()

    tms = time.time()
    for i in range(100):
        print(i)
        time.sleep(0.1)

        if not event_flag.is_set():
            s = input("Please input something:")
            print("You input {}".format(s))
            event_flag.set()
    tme = time.time()
    tm = round(tme - tms, 3)
    print()
    print("for loop running time:  {} s".format(tm))

    thread._stop()

추천

출처blog.csdn.net/Zhang_0702_China/article/details/124285831