-1

In Python, I am calling sub files from main python file. In all sub python files, I have included try and except block. In main file, I need the sub files to be executed in the order I have mentioned below. Is there a way to stop executing os.system("python SubFile2.py") statement, if any error is caught in os.system("python SubFile1.py") statement? And also I need to get the error details in the main python file.

This is the code snippet of main file:

import os
import sys

print("start here")
try:
    print('inside try')
    os.system("python SubFile1.py")
    os.system("python SubFile2.py")
    os.system("python SubFile4.py")
except:
    print("Unexpected error:")
    print(sys.exc_info()[0])
    print(sys.exc_info()[1])
    print(sys.exc_info()[2])
finally:
    print('finally ended')

Thanks in advance

user2906838
  • 1,178
  • 9
  • 20
Sanjay
  • 328
  • 1
  • 3
  • 13

1 Answers1

1

You should consider using [subprocess][1] It's not recommended to use os.system if you want to catch the exception and end another process, Because os.system() indicates a failure through the exit code of the method. For more detail you should consider reading this answer: Python try block does not catch os.system exceptions

For your workaround, you can try this code which works, however I have used subprocess.

import os
import sys
import subprocess

print("start here")



files = ["first.py", "second.py"]
count=0
for file in files:

    try:

        cmd = subprocess.Popen(["python", file],stdout=subprocess.PIPE,stderr=subprocess.PIPE)
        output, error = cmd.communicate()

        if(error):
            print(error)
            sys.exit()
    except OSError as e: 
        print("inside exception", e)
        sys.exit()
    count+=1 
user2906838
  • 1,178
  • 9
  • 20