What I want to happen is to run a script with the code sample in it, if scriptc does not run just append an error line to the stderr file and dump the calling script.
I run the below expecting it to attempt to run scriptc which does NOT exist, and then just dump to the exception and exit. BUT it doesn't run the exception code write to stderr and it doesn't exit(). It carries on and runs the code for scriptb which I don't want to run. Can someone tell me what I am doing wrong?
try:
out=subprocess.run(["python3",'scriptc.py'],stdout=fout,stderr=ferr, universal_newlines=True)
except:
sys.stderr.write("scriptc not run \n")
sys.exit()
fout=subprocess.run(["python3",'scriptb.py'],stdout=fout,stderr=ferr, universal_newlines=True)
subprocess.run
does not raise an exception if the process it runs returns a non-zero status code, which is the case here.
You should instead call the check_returncode
method of the returning CompletedProcess
object to raise a CalledProcessError
exception:
out=subprocess.run(["python3",'scriptc.py'],stdout=fout,stderr=ferr, universal_newlines=True)
try:
out.check_returncode()
except subprocess.CalledProcessError:
sys.stderr.write("scriptc not run \n")
sys.exit()