How to read keyboard input?

I would like to read data from the keyboard in Python

I am trying this:

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

But this does not work, neither with the eclipse, nor in the terminal, it always stops the question. I can dial the number, but after nothing happened.

You know why?

+115
python input keyboard
Mar 23 2018-11-11T00:
source share
5 answers

try

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

and if you want to have a numerical value, just convert it:

 try: mode=int(raw_input('Input:')) except ValueError: print "Not a number" 
+120
Mar 23 2018-11-11T00:
source share

It seems that you are mixing different Python here (Python 2.x vs Python 3.x) ... This is mostly correct:

 nb = input('Choose a number: ') 

The problem is that it is only supported in Python 3. As @sharpner said, for older versions of Python (2.x) you need to use the raw_input function:

 nb = raw_input('Choose a number: ') 

If you want to convert it to a number, try:

 number = int(nb) 

... although you need to consider that this may throw an exception:

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

And if you want to print the number using formatting, it is recommended to use Python 3 str.format() :

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

Instead:

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

But both parameters ( str.format() and % ) work in both Python 2.7 and Python 3.

+83
Mar 23 2018-11-12T00:
source share

Non-blocking, multi-threaded example:

Since locking keyboard input (since input() function blocks) is often not what we want to do (we often would like to continue to do other things), here is a very truncated multi-threaded example that demonstrates how to continue to run the main application while continuing to read data from the keyboard when they appear .

This works by creating a single thread to execute in the background, continuously calling input() and then passing all the received data to the queue.

Thus, your main thread remains to do whatever it wants, getting keyboard input from the first thread when there is something in the queue.

1. Sample Bare Python 3 code (no comment):

 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. The same Python 3 code as above, but with extensive explanatory comments:

 """ 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 - /questions/111246/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() 

Sample Output:

$ python3 read_keyboard_input.py
Ready for keyboard input:
Hello
input_str = hey
Hello
input_str = hello
7000
input_str = 7000
exit
input_str = output
Exit the serial terminal.
The end.

Recommendations:

  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: How do I subclass from a superclass?
  5. https://docs.python.org/3/library/queue.html
  6. https://docs.python.org/3.7/library/threading.html
+7
Nov 16 '18 at 20:09
source share

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

Since this is unsafe (due to eval), raw_input should be preferred for mission-critical applications.

+4
Mar 13 '14 at 18:55
source share

This should work

 yourvar = input('Choose a number: ') print('you entered: ' + yourvar) 
+4
Jul 12 '17 at 15:29
source share



All Articles