Opposite __init__ in the thread class

I understand that __init __ () is called automatically when you create a type class newThread = MyThread(property), and run () starts newthread.start(). What I'm looking for is what gets called automatically before the thread ends, so I don’t need to explicitly call self.cleanUp()return before each statement.

class MyThread(Thread): 

    def __init__(self, property): 
        Thread.__init__(self)
        self.property = property

    def cleanUp(self):
        # Clean up here

    def run(self):
        # Do some stuff
        self.cleanUp() # Current work around
        return
+6
source share
3 answers

One way to do this is to subclass Threadthe context manager as well . This will effectively make the __exit__()special method you want to call.

, . . property, , property - Python.

from threading import Thread
import time

TEST_THREAD_EXCEPTION = False  # change as desired

class MyThread(Thread):

    def __init__(self, attribute):
        Thread.__init__(self)
        self.attribute = attribute

    def cleanup(self):
        # Clean up here
        print('  cleaning up after thread')

    def run(self):
        if TEST_THREAD_EXCEPTION:
            raise RuntimeError('OOPS!')  # force exception
        print('  other thread now running...')
        time.sleep(2)  # Do something...

    def __enter__(self):
        try:
            self.run()
        except Exception as exc:
            print('Error: {} exception raised by thread'.format(exc))
            raise  # reraise the exception
        return self

    def __exit__(self, *args):
        self.cleanup()

print('main thread begins execution')
with MyThread('hello') as thread:
    print('doing other things in main thread while other thread is running')
print('main thread continuing...')

:

main thread begins execution
  other thread now running...
doing other things in main thread while other thread is running
  cleaning up after thread
main thread continuing on...

TEST_THREAD_EXCEPTION True, cleanup() , , , , , . :

main thread begins execution
Error: OOPS! exception raised by thread
Traceback (most recent call last):
  File "opposite_init.py", line 37, in <module>
    with MyThread('hello') as thread:
  File "opposite_init.py", line 27, in __enter__
    self.run()
  File "opposite_init.py", line 21, in run
    raise RuntimeError('OOPS!')  # force exception
RuntimeError: OOPS!
+6

Python, __del__ , with ,

, - (__del__()) - . , - , .

try... finally, finally .

class MyThread(Thread): 

    def __init__(self, property): 
        Thread.__init__(self)
        self.property = property

    def __enter__(self):
        return self

    def __exit__(self, exc_type, exc_value, traceback):
        print('starting cleanup')
        # Clean up here

    def run(self):
        # Do some stuff
        return

# not now you can call it like this:
with MyThread("spam") as spam:
    print("The thread is running")
    # you can also do stuff here

try... finally :

class MyThread(Thread): 

    def __init__(self, property): 
        Thread.__init__(self)
        self.property = property

    def cleanUp(self):
        # Clean up here
        print('starting cleanup')

    def run(self):
        # Do some stuff
        return

try:
    spam = MyThread('spam')
    print('The thread is running')
finally:
    spam.cleanUp()
+2

, , , run() , Thread, . - , :

class CleanupThread(Thread):
    def cleanup(self):
        # Override this method in your subclasses to do cleanup
        pass

    def run2(self):
        # Override this method in your subclasses instead of run()
        pass

    def run(self):
        # Do *not* override this in your subclasses. Override run2() instead.
        try:
            self.run2()
        finally:
            self.cleanup()

, run2 , .

Python , , .

+2
source

Source: https://habr.com/ru/post/1016558/


All Articles