如何在不杀死脚本的情况下停止 python 脚本?

how can I stop python script without killing it?

我想知道是否有办法在 python 脚本处于 运行 时停止它,而不用杀死它。

例如,我知道 ctrl + z or c 会终止当前进程..但我不想终止程序..

我的 python 程序一次获取一个文件并执行一些作业.. 每个文件大约需要 10~20 分钟,具体取决于文件的大小..并且目录中有很多文件..

但有时我必须让它完成当前正在处理的文件,在当前文件之后立即停止程序,而不是在工作过程中将其终止。

如何在 python 中执行此操作?如果可以的话,我想写这个 python 编码..

我试过了

if os.path.exists(filename)
    sys exit(0)

但是这个,我必须在它是 运行 时创建一个文件,这样当它到达那个文件时,它就会停止......但不是这样做......我想看看是否有更好的方法来阻止它。

Ctrl+Z 只会 suspend 进程,不会杀死它。您可以稍后键入 fg 来恢复它("fg" 代表 "foreground"。此外,您可以 运行 "bg" 代表 "background")。根据您的描述,这听起来是一个很好的解决方案,可以实现您的目标。

当然,这适用于任何过程,不仅python。

but sometimes I have to let it finish the file that it is currently working on stop the program right after that current file instead of killing it in the middle of the work.

这比Ctrl+Z更具体;您要求停止该程序,但不是立即停止。您可以为此使用信号。使用 signal 设置信号处理程序,并在命令行使用 kill -SIGWHATEVER 调用它。一般来说,信号处理程序应该只设置一个您定期检查的标志;它实际上不应该 "do anything" 本身,因为你不知道你的程序在被调用时处于什么状态。

信号处理程序是在您的程序接收到信号时调用的函数。它们是使用 signal.signal() 设置的。信号通过 kill 程序或 kill() 系统调用发送。您的处理程序将如下所示:

stop = False
def handler(number, frame):
    global stop
    stop = True
signal.signal(signal.SIGUSR1, handler)
for file in files:  # or whatever your main loop looks like
    # Process one file
    if stop:
        break

也可以catch Interrupt Exception(Ctrl+C)然后处理未完成的文件再出来

`def main():
    try:
        for file in file_list:
            process(file)
    except KeyboardInterrupt:
        process(file)
        raise Exception`