Pausing and resuming script execution with key press (python)

279 Views Asked by At

I have a script that controls an external machine with rather slow i/o operations. I'd like to be able to suspend and resume execution by pressing a key at any time, in such a way that execution of the current iteration in the loop is first completed, and the loop pauses before going on to the next iteration.

for i in iterable:
   foo(i)
   ## Pause if p is pressed
   ## resume if p is pressed again

Specifically, as the foo() subroutine takes several seconds, I would like the programme to listen for the key press even while it is executed. Is there a simple way to achieve this?

1

There are 1 best solutions below

0
zd_stackoverflow On

suspend python process by pressing hotkey F8:

;;;;AHK script to suspend process with hotkey 
Run, "python_script.py"
Sleep, 5000
F8::Process_Suspend(python_script)
F10::Process_Resume(python_pause.exe)
F11::Exitapp
Process_Suspend(PID_or_Name){
PID := (InStr(PID_or_Name,".")) ? ProcExist(PID_or_Name) : PID_or_Name

h:=DllCall("OpenProcess", "uInt", 0x1F0FFF, "Int", 0, "Int", pid)

If !h   

    Return -1

DllCall("ntdll.dll\NtSuspendProcess", "Int", h)

DllCall("CloseHandle", "Int", h)
}

Source: https://www.reddit.com/r/learnpython/comments/onc1jr/how_do_you_pause_and_continue_script_on_keypress/