简体   繁体   English

手动停止Python脚本时触发动作

[英]Trigger action when manually stopping Python script

I was searching for quite some time but I was unable to find a simple solution.我搜索了很长时间,但找不到简单的解决方案。 I have a python script that runs indefinitely and saves some files when a condition is met (enough data gathered).我有一个 python 脚本,它会无限期运行并在满足条件(收集到足够的数据)时保存一些文件。 Is there a way to terminate the execution of the script and trigger a function that would save the gathered (but yet unsaved) data?有没有办法终止脚本的执行并触发 function 来保存收集的(但尚未保存的)数据? Every time I have to do something (let's say close the computer), I must manually stop (terminate) script (in Pycharm) and I loose a part of the data which is not yet saved.每次我必须做某事(比如关闭计算机)时,我必须手动停止(终止)脚本(在 Pycharm 中)并且我丢失了一部分尚未保存的数据。

Edit: Thanks to @Alexander, I was able to solve this.编辑:感谢@Alexander,我能够解决这个问题。 A simple code that might better outline the solution:一个简单的代码可能会更好地概述解决方案:

import atexit
import time

@atexit.register
def on_close():
    print('success') #save my data

while True:
    print('a') 
    time.sleep(2)

Now when clicking on a Stop button, 'on_close' function is executed and I am able to save my data...现在,当单击“停止”按钮时,将执行“on_close”function,我可以保存我的数据...

Use the atexit module.使用atexit模块。 It part of the python std lib .它是python 标准库的一部分。

import atexit

@atexit.register
def on_close():
    ... do comething

atexit.register(func, *args, **kwargs)

Register func as a function to be executed at termination.将 func 注册为 function 以在终止时执行。 Any optional arguments that are to be passed to func must be passed as arguments to register().任何要传递给 func 的可选 arguments 必须作为 arguments 传递给 register()。 It is possible to register the same function and arguments more than once.可以多次注册相同的 function 和 arguments。

This function returns func, which makes it possible to use it as a decorator.这个 function 返回 func,这使得它可以用作装饰器。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM