What could be causing my code to loop twice when utilizing the keyboard?

Currently, I am developing a script that will notify the user when a specific sequence of numbers is inputted. The functionality appears to work correctly, however, it returns "1122334455" instead of the expected output of "12345":

import sys
sys.path.append('..')
import keyboard

line = ''
ISBN10 = ''
number = ""

def print_pressed_keys(e):
    global line, ISBN10, number
    line = line.join(str(code) for code in keyboard._pressed_events)
    if line == "2":
        number = 1
    elif line == "3":
        number = 2
    # Additional cases for other numbers omitted for brevity
    ISBN10 = ISBN10 + str(number)
    if len(ISBN10) > 10:
        ISBN10 = ISBN10[1:11]
    print("ISBN10: " + ISBN10)

keyboard.hook(print_pressed_keys)
keyboard.wait()

The current output displays:

ISBN10: 1
ISBN10: 11
ISBN10: 112
ISBN10: 1122
ISBN10: 11223
ISBN10: 112233

However, the correct output should be:

ISBN10: 1
ISBN10: 12
ISBN10: 123

Answer №1

The reason behind this behavior is that keyboard.hook() triggers its callback function both when a key is pressed and when it is released, resulting in two executions for every key press event. To ensure the callback runs only on key press events, you should modify your code as follows:

keyboard.on_press(print_pressed_keys)
# A hotkey has been added to allow exiting the block and continuing program execution
keyboard.wait("ESC") 
# This line will stop the hook from running after pressing the escape key to exit
keyboard.unhook_all() 

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

How come the "initialvel" property always stays the same as the "vel" attribute in the entire program?

During the development of my physics engine in Python pygame, I encountered a perplexing issue related to resetting the velocities and positions of particles (balls) when the 'r' key is pressed. Despite numerous tests and seeking advice from Chat ...

Unable to pass the Selenium driver as an argument to a function when utilizing `pool.starmap`

I am encountering an issue where I cannot pass a Selenium driver as an argument to a function using pool.starmap. Below is a simplified example to reproduce and verify the problem: Main code: from wait import sleep import multiprocessing from selenium im ...

Is "pass" equivalent to "return None" when using Python?

I've recently started delving into the realm of Python coding, and I have a question for you: Code def Foo(): pass def Bar(): return None Usage a = Foo() print(a) # None b = Bar() print(b) # None Question: 1. Despite having return None, ...

What distinguishes the delete and assign element functions in Python?

When it comes to refreshing a value, I'm curious about the best method to use. myList = [1, 2, 3] If I need to update the value of the list. One option is myList[2] = 5 Alternatively, del myList[2] myList[2] = 5 The elements in the list are obje ...

Django is successfully loading CSS, but images and javascript files are not found with a 404 error

Currently working on a Django website project where I have successfully created a login page. However, upon testing it on the development server, I noticed that the CSS loads perfectly fine, but the images and JavaScript files are returning a 404 error, ev ...

Utilizing Selenium to extract engagement data, such as likes and comments, from a photo on Facebook

Excited to obtain the specific content as outlined in the title. I have successfully figured out how to log in and retrieve photos from any profile I search for. However, I am facing an issue when trying to access comments or likes on selected photos. Desp ...

What could be causing the intermittent StaleElementReferenceException with Firefox when using splinter's is_text_present() function, while not experiencing the issue in Chrome or

Recently, I updated my test environment to the newest versions of selenium, splinter, and Firefox. However, one of my tests now shows failures about 80% of the time when using Firefox. The error message is as follows: Traceback (most recent call last): ...

Having trouble locating a document: Python, Django, and MongoDB collaboration

Feeling stuck on a simple issue in my small personal project. I have a MongoDB connected via Djongo and facing an issue with a collection using the generic Object ID. The view returns a 404 error, even though the same query directly in MongoDB fetches the ...

How to troubleshoot Python errors (+mod_wsgi) using the Chrome Network panel

As a newcomer to Python, I am facing an issue with viewing error messages. The problem arises when a javascript function is making a call as follows: $.getJSON('test.py', {data: 'somedata'}, function(return){alert(return.echo)}) In th ...

How to extract specific content from a website using Selenium and Python

I am having trouble retrieving the PREVIOUS ROLLS information from as I keep getting an empty array. Does anyone have any suggestions on how to successfully read this information? wait = WebDriverWait(self, 100) out = wait.until(EC.presence_of_element_ ...

Error encountered when importing Eclipse XLRD and XLWT modules

After downloading the most recent Enthought EPD python distribution (academic), which includes python 2.7, I decided to use Eclipse as my preferred IDE. I configured Eclipse to utilize this specific Python instance and proceeded to run the "images.py" exa ...

Is it possible to invoke a Python local function from an HTML document?

After creating a Python file with multiple functions, I am now working on designing a web page where I aim to trigger one of the functions mentioned earlier by clicking a button. However, I am unsure about how to go about this process. Is there anyone who ...

Is it possible to graph two dataframes of varying sizes side by side?

I am struggling with plotting two dataframes. One contains 20711 entries, while the other has 20710 entries. I have been attempting to plot using the following code: import pandas as pd import csv import matplotlib.pyplot as plt fig1 = plt.figure(figsize ...

Finding and substituting strings containing quotation marks in a pandas dataframe

In my dataframe, there is a column that contains lists of dictionaries. For example: [{'attr': 'color', 'value': 'BLUE'}] The issue is that the key-value pairs 'attr' and 'value' are not necessa ...

Bug in Bubble Sort Algorithm

I made an attempt at writing a bubble sort program but unfortunately, it doesn't seem to be working as expected. n = raw_input("please enter the number of elements you wish to add into the array") print 'enter the elements for the array that ne ...

What could be the reason for Firefox not utilizing the profile preferences when controlled through selenium?

I am attempting to use Selenium with Firefox to download PDF files. Despite having set my preferences as shown below, I am still encountering the "You have chosen to open" dialog box when running the code. This is not the expected behavior, as the settings ...

Guide to subtracting elements within a list

I have created a function that takes in a list of numbers such as [0.5, -0.5, 1] and then outputs a new list with each index containing the sum of the differences between the current value and all other values. For example, if the input is [0.5, -0.5, 1], ...

What are some efficient ways to read multiple lines from a file quickly in Python?

Currently, I am using the following Python code: file = open(filePath, "r") lines=file.readlines() file.close() If my file contains multiple lines (10,000 or more), my program tends to slow down when processing more than one file. Is there a way to optim ...

Tips for creating an HTML report using Python

Currently, I am searching for a solution to convert my saved matplotlib graphs as png files along with some data frames into HTML format. This is similar to how I typically use R2HTML in R. Despite my efforts, I have not been able to locate clear informat ...

What are the steps for adjusting the size of a frame using the cursor located inside it?

Is there a way to dynamically change the size of a QFrame based on the cursor position? For example: If the default width is set to 50, when the cursor hovers over the frame, the width should increase to 100. When the cursor moves outside of the frame, t ...