0

I have this function that will run for around an hour or so. I need a way to check for the keypress constantly while the store_data() function is running. The current code gives me a very small time frame to press the combination. Is there a way to keep checking for the keypress? The for loop goes on for like an hour or two and I need to constantly check for the keypress WHILE the function is being executed. I could use ctrl + c, but I dont want that. I want to raise a keyboard interrupt error when a certain key combination is pressed. Thank you

import keyboard
import time

def store_data():
        dict_of_data = []
        excel_file = read_excel()
        for word in excel_file:
            try:
                if keyboard.is_pressed('ctrl + alt + o'):
                    print("pressed")
                    raise KeyboardInterrupt("key interrupted")
                word_data = another_func(word)
                time.sleep(1)
            except KeyboardInterrupt:
                open_excel() #another func that i need to call if "ctrl + alt + o" is pressed and pause the current function
                word_data = another_func(symbol)
                pass
            dict_of_data.append(word_data)

        return dict_of_data
ARC4N3
  • 1
  • 2
  • I don't know if there is a specific way to do in python, but the standard approach for this long running processes (interrumpible or not) is to create a thread. For python, e.g. you can check [this tutorial](https://realpython.com/intro-to-python-threading/) – Sourcerer Jan 30 '21 at 10:03
  • Does this answer your question? [How to kill a while loop with a keystroke?](https://stackoverflow.com/questions/13180941/how-to-kill-a-while-loop-with-a-keystroke) – Daan Seuntjens Jan 30 '21 at 10:14
  • @DaanSeuntjens I dont really wanna kill the loop, I wanna pause it so I can call another function and the continue the loop. Every loop takes around 2 seconds, and there's a very small window of time frame for me to use keyboard.is_pressed('some key'). – ARC4N3 Jan 30 '21 at 13:31
  • @Sourcerer I did in fact try threading, but I was not able to call the other function while the first one was running using the keypress combination. It could be possible that I didn't implement it correctly considering i'm fairly new to threading. I'll give it a try again. Thanks! – ARC4N3 Jan 30 '21 at 13:38

1 Answers1

0

Hotkeys seem to have solved the problem. Also, I dont have to raise the KeyboardInterrupt error. The code here seems to have worked fine.

def func_called():
    print("worked")
    another_func()
    pass


def store_data():
    dict_of_data = []
    excel_file = read_excel()
    keyboard.add_hotkey('ctrl + alt + o', func_called)
    for symbol in excel_file:
        word_data = func(word)
        time.sleep(1)
        dict_of_data.append(word_data)
        
    return dict_of_data
ARC4N3
  • 1
  • 2