development

키보드 입력을 읽는 방법?

big-blog 2020. 7. 22. 07:35
반응형

키보드 입력을 읽는 방법?


파이썬에서 키보드에서 데이터를 읽고 싶습니다

나는 이것을 시도한다 :

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

그러나 그것은 일식이나 터미널에서 작동하지 않으며 항상 질문을 중단합니다. 나는 숫자를 입력 할 수 있지만 아무 일도 일어나지 않으면.

왜 그런지 아십니까?


시험

raw_input('Enter your input:')  # If you use Python 2
input('Enter your input:')      # If you use Python 3

숫자 값을 원하면 변환하십시오.

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

여기에 다른 Python을 혼합하고있는 것 같습니다 (Python 2.x 대 Python 3.x) ... 이것은 기본적으로 맞습니다.

nb = input('Choose a number: ')

문제는 Python 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")

그리고 서식을 사용하여 숫자를 인쇄하려면 Python 3 str.format()에서 권장됩니다.

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

대신에:

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

그러나 옵션 ( str.format()%)은 모두 Python 2.7 및 Python 3에서 작동합니다.


비 차단 멀티 스레드 예 :

( input()함수 블록 때문에) 키보드 입력을 차단하는 것이 종종 우리가하고 싶은 일 아니기 때문에 (우리는 다른 일을 계속하고 싶습니다), 여기에는 매우 잘 고정 된 멀티 스레드 예제있습니다. 도착할 때마다 키보드 입력을 읽는 동안 주 응용 프로그램 .

백그라운드에서 실행할 하나의 스레드를 작성하고 지속적으로 호출 input()한 다음 수신 한 데이터를 큐에 전달합니다.

이런 식으로 메인 스레드는 원하는 것을 수행하고 대기열에 무언가가있을 때마다 첫 번째 스레드에서 키보드 입력 데이터를받습니다.

1. 맨손으로 파이썬 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()

2. 위와 동일한 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()

샘플 출력 :

$ python3 read_keyboard_input.py
키보드 입력 준비 :
hey
input_str = hey
hello
input_str = hello
7000
input_str = 7000
exit
input_str = exit
직렬 터미널을 종료합니다.
종료.

참고 문헌 :

  1. https://pyserial.readthedocs.io/en/latest/pyserial_api.html
  2. ***** https://www.tutorialspoint.com/python/python_multithreading.htm
  3. ***** https://ko.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

관련 / 교차 연결 :

  1. PySerial non-blocking read loop

input([prompt]) is equivalent to eval(raw_input(prompt)) and available since python 2.6

As it is unsafe (because of eval), raw_input should be preferred for critical applications.


This should work

yourvar = input('Choose a number: ')
print('you entered: ' + yourvar)

참고URL : https://stackoverflow.com/questions/5404068/how-to-read-keyboard-input

반응형