How to quit or change a variable during a step of the loop by key press in python

34 Views Asked by At

I have been making a program that reads some documents and deletes or writes another file after doing some process. For each html file, the program tries some process, and if there is a fault, then it deletes the file. If not, then it writes a summary of the original document.

To do that, I need to use a for loop. Moreover during the loops, the program shows me the contents of the documents, and I could check that this documents will be deleted or not. To save the time, I would like to skip the step if I know that, since each step takes a long time.

I try to use pynput module and threading method, but most of examples only explain cases that each step of the loop is not that long an not for a sequential process.

I expect that it works like Keyboard interrupt exception in console. If I press some buttons, then the program detects the key press and changes some variables, and then finally a step acts as expected. But it doesn't work like that.

My first trial is like this (a python-like pseudocode.):

import os
import time
import threading

from pynput import keyboard 

def press_enable(key):
    global delete_flag
    global kill_process 
    if key == keyboard.Key.esc:
        kill_process = True
        quit()
    if delete_flag:
        if key == 'd':
            delete_flag = False
    else:
        if key == 'd':
            delete_flag = True
    return

def loop():
    file_list = []
    for file in file_list:
        #1
        show_file(file)
        file = foo1(file)
        time.sleep(10)
        if delete_flag:
            delete(file)
            delete_flag = False
            continue
        #2
        file = foo2(file)
        time.sleep(10)
        if delete_flag:
            delete(file)
            delete_flag = False
            continue
        #3
        file = foo3(file)
        time.sleep(10)
        if delete_flag:
            delete(file)
            delete_flag = False
            continue
        #... and local variable flag is introduced
        if flag:
            delete(file)
        else:
            write_file(summary_of_file)
        close_file(file)

if __name__ == "__main__":
    delete_flag = False
    kill_process = True
    listener = keyboard.Listener(on_press=press_enable)
    listener.start()
    
    thread = threading.Thread(target=loop)
    thread.daemon = True
    thread.start()
    thread.join()

Like keyboard Interrupt, I would like to change the states at any moment while a step of the loop is running, and if it's impossible, at least at some certain points of the step.

0

There are 0 best solutions below