Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/313.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/file/3.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 如何保证在程序关闭前执行某些代码?_Python_File_Python 3.x - Fatal编程技术网

Python 如何保证在程序关闭前执行某些代码?

Python 如何保证在程序关闭前执行某些代码?,python,file,python-3.x,Python,File,Python 3.x,我知道使用with语句将保证打开的文件被关闭,但我如何保证,例如,程序的活动数据在程序终止之前写入文件并保存?您想使用该模块吗。例如,您可以执行以下操作: def cleanup(): #do cleanup here # In main somewhere: atexit.register(cleanup) 这将在程序终止时执行清理功能 哇,知道这件事真好。尽管我希望能够更好地理解什么是“当程序被Python未处理的信号终止时,当检测到Python致命内部错误时,或者当调用os.

我知道使用
with
语句将保证打开的文件被关闭,但我如何保证,例如,程序的活动数据在程序终止之前写入文件并保存?

您想使用该模块吗。例如,您可以执行以下操作:

def cleanup():
    #do cleanup here


# In main somewhere:
atexit.register(cleanup)

这将在程序终止时执行清理功能

哇,知道这件事真好。尽管我希望能够更好地理解什么是“当程序被Python未处理的信号终止时,当检测到Python致命内部错误时,或者当调用os._exit()时,不调用通过此模块注册的函数。”例如,什么算为“Python未处理的信号”,或者“Python致命内部错误”?SIGSEG、SIGKILL(
kill-9
)、SIGBUS等是任何程序都无法继续运行的东西。这意味着,例如,如果您从外部实用程序(如操作系统上的进程列表)手动终止进程,它不被调用。换句话说,
atexit
只有在程序被要求“很好地”退出而不是强制终止时才起作用。是的。例如,许多程序将自己锁定在一个循环中,从不检查
ctrl+c
信号,因此按
ctrl+c
不会导致它们停止。事实上,在纯命令上,line界面,
ctrl+c
将是“很好地”退出程序的唯一方法,因为GUI窗口上没有文件菜单或“x”按钮。