it-source

키보드 입력을 읽는 방법?

criticalcode 2023. 9. 3. 16:21
반응형

키보드 입력을 읽는 방법?

저는 파이썬의 키보드에서 데이터를 읽고 싶습니다.나는 이 코드를 시도했습니다.

nb = input('Choose a number')
print('Number%s \n' % (nb))

하지만 일식이나 단말기에서는 작동하지 않습니다. 항상 질문의 끝입니다.번호를 입력할 수 있지만 아무 일도 일어나지 않습니다.

왠지 알아?

사용하다

input('Enter your input:')

Python 3을 사용하는 경우.

숫자 값을 사용하려면 다음과 같이 변환합니다.

try:
    mode = int(input('Input:'))
except ValueError:
    print("Not a number")

2를 하는 경우에는 Python .raw_inputinput.

여기서 서로 다른 파이썬(파이썬 2.x 대 파이썬 3.x)을 혼합하고 있는 것 같습니다.이것은 기본적으로 정확합니다.

nb = input('Choose a number: ')

문제는 파이썬 3에서만 지원된다는 점입니다.@sharpner가 대답했듯이 이전 버전의 Python(2.x)의 경우 다음 기능을 사용해야 합니다.raw_input:

nb = raw_input('Choose a number: ')

이 값을 숫자로 변환하려면 다음을 시도해야 합니다.

number = int(nb)

이 경우 예외가 발생할 수 있다는 점을 고려해야 합니다.

try:
    number = int(nb)
except ValueError:
    print("Invalid number")

포맷을 에서 그고리포사인싶다고, 파썬이 3.str.format()권장:

print("Number: {0}\n".format(number))

다음 대신:

print('Number %s \n' % (nb))

하지만 두 가지 옵션 모두(str.format()그리고.% 23에서 합니다.)는 Python 2.7과 Python 3에

비차단, 멀티 스레드 예제:

키보드 입력에 대한 차단으로(이후)input()기능 블록)은 종종 우리가 하고 싶은 것이 아닙니다(다른 작업을 계속하고 싶은 경우가 많습니다). 여기에 메인 응용 프로그램이 도착할 때마다 키보드 입력을 계속 읽는 방법을 보여주는 매우 간단한 다중 실행 예제가 있습니다.여기서 eRCaGuy_PyTerm 직렬 터미널 프로그램에서 이 기술을 사용합니다(코드 검색).

이것은 백그라운드에서 실행할 하나의 스레드를 만들고 계속 호출함으로써 작동합니다.input()수신한 모든 데이터를 대기열로 전달합니다.

이렇게 하면 메인 스레드는 대기열에 무언가가 있을 때마다 첫 번째 스레드로부터 키보드 입력 데이터를 수신하여 원하는 모든 작업을 수행할 수 있습니다.

베어 파이썬 3 코드 예(댓글 없음):

import threading
import queue
import time

def read_kbd_input(inputQueue):
    print('Ready for keyboard input:')
    while (True):
        input_str = input()
        inputQueue.put(input_str)

def main():
    EXIT_COMMAND = "exit"
    inputQueue = queue.Queue()

    inputThread = threading.Thread(target=read_kbd_input, args=(inputQueue,), daemon=True)
    inputThread.start()

    while (True):
        if (inputQueue.qsize() > 0):
            input_str = inputQueue.get()
            print("input_str = {}".format(input_str))

            if (input_str == EXIT_COMMAND):
                print("Exiting serial terminal.")
                break
            
            # Insert your code here to do whatever you want with the input_str.

        # The rest of your program goes here.

        time.sleep(0.01) 
    print("End.")

if (__name__ == '__main__'): 
    main()

위와 동일한 Python 3 코드이지만 광범위한 설명이 있습니다.

"""
read_keyboard_input.py

Gabriel Staples
www.ElectricRCAircraftGuy.com
14 Nov. 2018

References:
- https://pyserial.readthedocs.io/en/latest/pyserial_api.html
- *****https://www.tutorialspoint.com/python/python_multithreading.htm
- *****https://en.wikibooks.org/wiki/Python_Programming/Threading
- https://stackoverflow.com/questions/1607612/python-how-do-i-make-a-subclass-from-a-superclass
- https://docs.python.org/3/library/queue.html
- https://docs.python.org/3.7/library/threading.html

To install PySerial: `sudo python3 -m pip install pyserial`

To run this program: `python3 this_filename.py`

"""

import threading
import queue
import time

def read_kbd_input(inputQueue):
    print('Ready for keyboard input:')
    while (True):
        # Receive keyboard input from user.
        input_str = input()
        
        # Enqueue this input string.
        # Note: Lock not required here since we are only calling a single Queue method, not a sequence of them 
        # which would otherwise need to be treated as one atomic operation.
        inputQueue.put(input_str)

def main():

    EXIT_COMMAND = "exit" # Command to exit this program

    # The following threading lock is required only if you need to enforce atomic access to a chunk of multiple queue
    # method calls in a row.  Use this if you have such a need, as follows:
    # 1. Pass queueLock as an input parameter to whichever function requires it.
    # 2. Call queueLock.acquire() to obtain the lock.
    # 3. Do your series of queue calls which need to be treated as one big atomic operation, such as calling
    # inputQueue.qsize(), followed by inputQueue.put(), for example.
    # 4. Call queueLock.release() to release the lock.
    # queueLock = threading.Lock() 

    #Keyboard input queue to pass data from the thread reading the keyboard inputs to the main thread.
    inputQueue = queue.Queue()

    # Create & start a thread to read keyboard inputs.
    # Set daemon to True to auto-kill this thread when all other non-daemonic threads are exited. This is desired since
    # this thread has no cleanup to do, which would otherwise require a more graceful approach to clean up then exit.
    inputThread = threading.Thread(target=read_kbd_input, args=(inputQueue,), daemon=True)
    inputThread.start()

    # Main loop
    while (True):

        # Read keyboard inputs
        # Note: if this queue were being read in multiple places we would need to use the queueLock above to ensure
        # multi-method-call atomic access. Since this is the only place we are removing from the queue, however, in this
        # example program, no locks are required.
        if (inputQueue.qsize() > 0):
            input_str = inputQueue.get()
            print("input_str = {}".format(input_str))

            if (input_str == EXIT_COMMAND):
                print("Exiting serial terminal.")
                break # exit the while loop
            
            # Insert your code here to do whatever you want with the input_str.

        # The rest of your program goes here.

        # Sleep for a short time to prevent this thread from sucking up all of your CPU resources on your PC.
        time.sleep(0.01) 
    
    print("End.")

# If you run this Python file directly (ex: via `python3 this_filename.py`), do the following:
if (__name__ == '__main__'): 
    main()

샘플 출력:

pypython3 read_input.py
키보드 입력 준비:
하세요.
= heyinput_str = 헤이
안녕하세요.
= helloinput_str = 명령어
7000
= 7000input_str = 7000
출입구
= exit input_str = 종료
직렬 터미널을 종료하는 중입니다.
끝.

Python Queue 라이브러리는 스레드 세이프입니다.

참고:Queue.put()그리고.Queue.get()그리고 다른 큐 클래스 메소드들은 모두 스레드 세이프입니다! (이것은 C++의 표준 템플릿 라이브러리에 있는 큐들과 다른 컨테이너들과는 다릅니다!) Python 큐 클래스와 그 메소드들은 스레드 세이프이기 때문에, 그들은 스레드 간 작업에 필요한 모든 내부 잠금 시맨틱을 구현하므로, 큐 클래스의 각 함수 호출은 콘세이프가 될 수 있습니다.단일 원자력 작업으로 간주됩니다.설명서 상단에 있는 참고 사항을 참조하십시오. https://docs.python.org/3/library/queue.html (추가됨):

대기열 모듈은 다중 생산자, 다중 소비자 대기열을 구현합니다.여러 스레드 간에 정보를 안전하게 교환해야 하는 경우 스레드 프로그래밍에서 특히 유용합니다.모듈의 큐 클래스는 필요한 모든 잠금 의미를 구현합니다.

참조:

  1. https://pyserial.readthedocs.io/en/latest/pyserial_api.html
  2. *******https://www.tutorialspoint.com/python/python_multithreading.htm
  3. *******https://en.wikibooks.org/wiki/Python_Programming/Threading
  4. 파이썬: 어떻게 슈퍼클래스에서 서브클래스를 만들 수 있습니까?
  5. https://docs.python.org/3/library/queue.html
  6. https://docs.python.org/3.7/library/threading.html
  7. [위에 제시된 기술과 코드를 사용하는 My repo] https://github.com/ElectricRCAircraftGuy/eRCaGuy_PyTerm

관련/교차 연결:

  1. [myanswer] PySerial 논블로킹 읽기 루프

변수를 사용하여 간단히 입력() 함수를 사용할 수 있습니다.빠른 예!

user = input("Enter any text: ")
print(user)

저는 한 글자를 읽는 법을 찾아 여기에 왔습니다.

저는 이 질문에 대한 답을 바탕으로 리드차 라이브러리를 찾았습니다.파이프 설치 후:

import readchar

key = readchar.readkey()

언급URL : https://stackoverflow.com/questions/5404068/how-to-read-keyboard-input

반응형