确定python是否正在退出
有没有办法确定python是否正在关闭 基本上:确定python是否正在退出,python,destructor,Python,Destructor,有没有办法确定python是否正在关闭 基本上: def Foo(object): def __del__(self): if PYTHON_IS_EXITING: do_this else: do_that foo1 = Foo() del foo1 # calls do_that foo2 # calls do_this when python exits 上下文是多处理的。当python退出时,线程池不工作,do_将并行执行,而do_将串行执
def Foo(object):
def __del__(self):
if PYTHON_IS_EXITING:
do_this
else:
do_that
foo1 = Foo()
del foo1 # calls do_that
foo2 # calls do_this when python exits
上下文是多处理的。当python退出时,线程池不工作,do_将并行执行,而do_将串行执行
谢谢您可以尝试使用
atexit
import atexit
def stufftodowhenpythonquits():
# do some stuff
atexit.register(stufftodowhenpythonquits)
在亚当·斯密所说的基础上 如果您安排atexit拆除您的对象,那么很有可能您不需要做任何不同的事情。因为当atexit运行其注册函数时,您想要使用的线程池还没有被拆毁。因此,atexit注册函数可以(可能)完全执行析构函数在退出前调用时应该执行的操作 但是等等,还有更多 考虑以下在退出前与退出时处理物体拆卸的轻微不明智尝试:
#!/usr/bin/python3
import atexit
class Foo:
def __init__(self):
self.dead = False
atexit.register(self.atexit)
def __del__(self):
print("%s: in destructor, self.dead is %s"%(id(self), self.dead))
if not self.dead: self.atexit()
def atexit(self):
print("%s: in atexit"%id(self))
self.dead = True
atexit.unregister(self.atexit)
# Do whatever end-of-life processing you need here. Whether
# we got here from our destructor or the atexit modules
# processing, whatever resources we need should (probably)
# still be available.
foo1 = Foo()
foo2 = Foo()
print("foo1: %s, foo2: %s"%(id(foo1), id(foo2)))
del foo1
如果运行此命令,您将看到在调用析构函数时,这两个对象都已经调用了atexit()方法。这是因为,由于对象的atexit()方法是在atexit模块中注册的,因此atexit模块持有对该对象的引用。因此,即使在del之后,对象也会一直保留到退出
如果您不太需要快速垃圾收集,那么这可能没问题。(在这种情况下,您可以去掉self.dead标志和析构函数。因为在atexit调用对象分解之前,无论如何都不会调用析构函数,所以在调用析构函数时,总是没有什么事情可做。)
如果您确实需要对象在退出之前离开--那么,将其作为练习留给读者。:-)