Try subprocess with the check=True
option:
From the subprocess docs:
If check is true, and the process exits with a non-zero exit code, a
CalledProcessError exception will be raised. Attributes of that
exception hold the arguments, the exit code, and stdout and stderr if
they were captured.
If B.py is something like:
print("HELLO from B")
raise Exception("MEH")
Then A.py could be something like:
import subprocess
try:
print("TRYING B.py")
subprocess.run(["python", "B.py"], check=True)
except subprocess.CalledProcessError as cpe:
print("OH WELL: Handling exception from B.py")
print(f"Exception from B: {cpe}")
The result:
~ > python A.py
TRYING B.py
HELLO from B
Traceback (most recent call last):
File "B.py", line 2, in <module>
raise Exception("MEH")
Exception: MEH
OH WELL: Handling exception from B.py
Exception from B: Command '['python', 'B.py']' returned non-zero exit status 1.
To silence the exception from display, change B.py to the following:
import os
import sys
sys.stderr = open(os.devnull, 'w')
print("HELLO from B")
raise Exception("MEH")
The result:
~ > python A.py
TRYING B.py
HELLO from B
OH WELL: Handling exception from B.py
Exception from B: Command '['python', 'B.py']' returned non-zero exit status 1.