Nan Hua
Nan Hua

Reputation: 3664

How to run some thing before program ends in python

What's the suggested way to do just before the program ends in Python?

e.g. in c++, I can do something like

struct Cleanup { ~Cleanup() { ..do something..} };
....In some function... {
  static Cleanup cleanup; // this will be cleaned when program ends.
}

(I'm not sure whether the way above is a legitimate way in C++ but it seems working for me).

Upvotes: 0

Views: 119

Answers (2)

orangeInk
orangeInk

Reputation: 1400

Since you were specifically asking about the program finishing you may also want to look at the built-in atexit module.

https://docs.python.org/3/library/atexit.html

Upvotes: 2

Jiun Bae
Jiun Bae

Reputation: 550

Search about python destructor.

class Package:
    ...
    def __del__(self):
        pass

    def __exit__(self, exc_type, exc_value, traceback):
        pass

or decorator

@SomeDecorator
def function():
    pass

def SomeDecorator(func):
    def wrapper(self, *args, **kwargs):
        func(self, *args, **kwargs)
        # after func
return wrapper

Upvotes: 0

Related Questions