I would like to write a python code that run several functions sequentially. Actually, start from first function and check if it doesn't throw any error, then start running second function and so on. I used following strategy, but it didn't stop when first function throws error and keep running other function:
try:
firstFunc()
except:
raise ExceptionFirst('job failed!')
else:
try:
secondFunc()
except:
raise ExceptionSecond('second function failed!')
------------------------------ ADD-ON-------------------------------------------
All functions defined in a separate way and don't have connection with each other. The structure of each function is like following (e.g., first fucntion):
p = subprocess.Popen("abaqus script=py.py", shell=True)
p.communicate() #now wait
if p.returncode == 0:
print("job is successfully done!")
I changed my function as follows and it worked successfully:
p = subprocess.check_call("abaqus script=py.py", shell=True)
if p == 0:
print("job is successfully done!")
But, I stuck with the same problem for one of my functions which has following structure:
p = subprocess.check_call("java -jar javaCode.jar XMLfile.xml", shell=True)
if p == 0:
print("job is successfully done!")
It throws an error, but the python print out "job is successfully done!" for that and keeps running other functions!!
---------------------------------------- Full Code ------------------------------------------------
import subprocess
import sys, os
def abq_script():
p = subprocess.check_call("abaqus script=py.py", shell=True)
if p == 0:
print("job is successfully done!\n")
def abq_java():
p = subprocess.check_call("java -jar FisrtJavaCode.jar", shell=True)
if p == 0:
print("job is successfully done!\n")
def java_job():
p = subprocess.check_call("java -jar secondJavaCode.jar XMLfile.xml", shell=True)
if p == 0:
print("job is successfully done!\n")
def abq_python_java():
funcs = [abq_script, abq_java, java_job]
exc = Exception('job failed!')
for func in funcs:
try:
func()
except Exception as e:
print(str(e))
break
If the first or second function shows an error, the exception throws an exception and program stops from running. But, if last function (java_job) shows an error, program doesn't throw any exception and keeps running.