R
R
r1dddy4sv2021-09-30 15:44:54
Python
r1dddy4sv, 2021-09-30 15:44:54

Multiprocessing cause error inside process?

Is it possible to somehow stop the Process by causing an error?
The fact is that at the end of the multiprocess.Process session, I would like the action shown in finally to be performed:

def drop(args):
    try:
         # do something
         driver=**anything**
         #do something 
    except:
          pass
    finally:
         driver.do_anything()


For now, I'm stopping the session like this:
s.terminate()
s.join() 
#Здесь должно выполнится driver.do_anything()


Is it possible to somehow cause an error inside the session, so that the finally or except condition would be fulfilled?

Thanks

Answer the question

In order to leave comments, you need to log in

2 answer(s)
L
LXSTVAYNE, 2021-09-30
@r1dddy4sv

You can write a custom process using a context manager.
The __enter__() method is executed at the start, and __exit__() is always at the exit of the context manager, you can catch your mistakes in it and take the necessary actions.

from multiprocessing import Process


class CustomProcess(Process):
    def __init__(self):
        super().__init__()

    def __enter__(self):
        return self

    def __exit__(self, exc_type, exc_val, exc_tb):
        print(exc_type, exc_val, exc_tb)
        print("Посмертное действие")


if __name__ == '__main__':
    with CustomProcess() as process:
        raise Exception("Some Value")

V
Viktor Golovanenko, 2021-09-30
@drygdryg

Create a custom exception and throw it in a try block:

class MyException(Exception):
    pass


def drop(args):
    try:
         # do something
         driver=**anything**
         #do something 
         raise MyException
    except MyException:
          pass
    finally:
         driver.do_anything()

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question