0
import time
from multiprocessing import Process


def possible_error_causer(a, b):
    time.sleep(5)
    c = a / b
    print(c)
    time.sleep(100)


for i in range(3):
    p = Process(target=possible_error_causer, args=(i, i))
    p.start()

The code above will execute after an exception occured in process that received 0, 0 as arguments (will run 100 seconds after that). But I want script to stop when there is error in any process. Try except is not an option (sys.exit() in except), because it doesn't catch all external errors (eg it doesn't catch some OpenCV errors)

Jedi Knight
  • 367
  • 2
  • 10
  • 1
    This could be of potential help: [Python multiprocessing: how to exit cleanly after an error?](https://stackoverflow.com/questions/23716951/python-multiprocessing-how-to-exit-cleanly-after-an-error) – Trooper Z Nov 16 '22 at 15:38

2 Answers2

0

I didn't succeed with that exactly, as I would probably need to collect processes objects in main thread and then pass them to child processes via Queue and calling terminate on them after except (yes, I gave up other than try except, sys.excepthook didn't work for me).

However, as I didn't need async to be exactly multiprocessing, I just replaced it with threading.Thread and called os._exit(1) in except.

import sys
import time
import os
from threading import Thread


def myexcepthook(*args):
    # Meant for sys.excepthook in multiprocessing script, but didn't work
    print("My except worked")


def possible_error_causer(a, b):
    try:
        time.sleep(5)
        c = a / b
        print(c)
        time.sleep(100)
    except:
        os._exit(1)



for i in range(3):
    p = Thread(target=possible_error_causer, args=(i, i))
    p.start()
Jedi Knight
  • 367
  • 2
  • 10
0

You are performing a division by zero. Indeed, in the first call to subprocess you pass (, i, ) which translates to a = i and b = i with i = 0.

To fix this you can either:

  • change the range to range(1, 4) so that you iterate from 1 to 4 excluded.
  • add one to b args=(i, i+1) to ensure the divisor if not 0.
Jib
  • 1,334
  • 1
  • 2
  • 12