gpt4 book ai didi

python - 如何让用户在预定义的点暂停 python 脚本?

转载 作者:太空宇宙 更新时间:2023-11-03 15:33:36 24 4
gpt4 key购买 nike

假设我有很多工作要做,所以我想为用户提供暂停和/或停止工作的选项。但我不想以不一致的状态结束,所以我只能在程序的某些点暂停和退出。

我将如何实现一个可以如下使用的 user_requested_pa​​use() 方法?

for item in some_very_large_list:
do_work()
# can't stop here
do_more_work()
# now we could pause.
if user_requested_pause():
# ask user how to proceed, then continue or exit with consistent state

我考虑过只使用 ctrl+c,但 KeyboardInterrupt 可能随时发生。

理想情况下,我会检查 stdin 上是否有可用的输入,但我还没有找到这样做的方法。 read() 只是在没有输入时阻塞,即使用户不希望它暂停程序。

编辑:我是这样解决的:

import signal
pause_requested = False
def handler(signum, frame):
global pause_requested
pause_requested = True
for item in some_very_large_list:
do_work()
do_more_work()
if pause_requested:
# ask user how to proceed, then continue or exit with consistent state
pause_requested = False

最佳答案

您可以使用 the signal module为此,通过让处理程序设置一个标志来告诉程序暂停并等待输入。

关于python - 如何让用户在预定义的点暂停 python 脚本?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56276709/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com