Как читать ввод с клавиатуры? - PullRequest
115 голосов
/ 23 марта 2011

Я хотел бы прочитать данные с клавиатуры в Python

Я пытаюсь это:

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

Но это не работает, ни с затмением, ни в терминале, это всегдаостановка вопроса.Я могу набрать номер, но после того, как ничего не произойдет.

Знаете ли вы, почему?

Ответы [ 5 ]

119 голосов
/ 23 марта 2011

попробуй

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"
83 голосов
/ 23 марта 2011

Кажется, что вы смешиваете здесь разные питоны (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.

8 голосов
/ 16 ноября 2018

Неблокирующий, многопоточный пример:

Поскольку блокировка ввода с клавиатуры (поскольку функциональные блоки input()) часто не , что мы хотим сделать (мы бычасто любят продолжать заниматься другими делами), вот очень урезанный многопоточный пример , чтобы продемонстрировать , как продолжать работу с основным приложением, продолжая при этом читать на клавиатурных входах, когда они поступают .

Это работает, создавая один поток для работы в фоновом режиме, непрерывно вызывая input(), а затем передавая все полученные данные в очередь.

Таким образом, ваш основной поток остается делать все, что захочет, получая входные данные клавиатуры из первого потока, когда в очереди что-то есть.

1.Пример кода Bare Python 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
- /905747/python-kak-mne-sdelat-podklass-iz-superklassa
- 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
Готов к вводу с клавиатуры:
эй
input_str = эй
привет
input_str = привет
7000
input_str = 7000
выход
input_str = выход
выход из последовательного терминала.
End.

Ссылки:

  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. Python: Как сделать подкласс из суперкласса?
  5. https://docs.python.org/3/library/queue.html
  6. https://docs.python.org/3.7/library/threading.html
4 голосов
/ 12 июля 2017

Это должно работать

yourvar = input('Choose a number: ')
print('you entered: ' + yourvar)
4 голосов
/ 13 марта 2014

input([prompt]) эквивалентно eval(raw_input(prompt)) и доступно с python 2.6

Поскольку это небезопасно (из-за eval), raw_input должен быть предпочтительным для критических приложений.

...