通过按键暂停和恢复脚本执行(python)

问题描述 投票:0回答:1

我有一个脚本可以控制 I/O 操作相当慢的外部机器。我希望能够通过随时按键来暂停和恢复执行,这样循环中当前迭代的执行首先完成,循环在继续下一次迭代之前暂停。

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

具体来说,由于 foo() 子例程需要几秒钟的时间,我希望程序即使在执行时也能监听按键。 有没有简单的方法可以实现这一目标?

python keyboard-events pausing-execution
1个回答
0
投票

按热键 F8 暂停 python 进程:

;;;;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)
}

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

© www.soinside.com 2019 - 2024. All rights reserved.