Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to catch an error in batch file running inside python script

I have Python script that calls several batch files through os.system. However, sometimes the batch file will throw errors and exit via exit /b 1.

However, even though the batch script fails, the Python script continues running, but I’d like the entire python script to quit as well if any batch script throws an error. How do I catch this exception in Python?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

os.system‘s return value is (usually. There are some caveats so you should check out the docs).

It can be used to catch the exit 1 in the batch script:

import os

exit_code = os.system('./some_batch_script')

if exit_code != 0:
    raise Exception(f'batch script exited with {exit_code}')
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading