0

I want to capture the pressed key and do different tasks if it for example is '1' or '2', etc.

This is my sample code:

import keyboard

key = keyboard.read_key()
if key == '1':
    print('something')
elif key == '2':
    print('something')
else:
    print('something')
    
str = input('Type something: ')

It works fine but for example when I press key '1', when the last line (input) runs, the output is like this (Terminal):

Type something: 1

Why Python automatically puts '1' at the end and how can I get rid of it?

Appreciate any help!

4
  • No module named 'keyboard'. Which library do you use ? Commented Nov 13, 2022 at 18:21
  • Installed it through the 'pip install keyboard' command Commented Nov 13, 2022 at 18:25
  • Sorry. Too difficult to reproduce. Need to be root on Linux. Commented Nov 13, 2022 at 18:40
  • keyboard is intended to capture and send keyboard events going to other programs. It doesn't actually consume the event, as that would make it useless for its intended purpose. Commented Nov 13, 2022 at 18:43

2 Answers 2

0

You could try swapping keyboard.read_key() for the keyboard.is_pressed() function to process the input, depending on the keys pressed

The post below might help more:

How to detect key presses?

Sign up to request clarification or add additional context in comments.

1 Comment

keyboard.is_pressed() waits just for a specific key, while the purpose is to execute different codes based on different inputs!
0

It automatically puts a 1 at the end because that is what you typed into the terminal. To verify this, try pressing backspace and seeing if you can delete the 1. If you type into the terminal when code is running, even if it isn't an input function, it will remember what you typed and paste that in when an input is called. To avoid this, simply don't have focus on the terminal when running and testing the code.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.