Home > other >  Detect an error and raise flag in Python when running an Matlab script from Python
Detect an error and raise flag in Python when running an Matlab script from Python

Time:11-29

I have a Matlab script that I am running it from Python. I want to detect any error happening in my Matlab script and raise a flag in Python (e.g. e = "error message from Matlab" and print(e) or if error_in_matlab: e=1). Here is my simplified code to run my yyy.m matlab script:

import os
path_to_mfile = '/Users/folder/yyy'
matlabCommandStr = 'matlab -nodisplay -r "clear all; close all; run(\'{}\'); quit" '.format(path_to_mfile)

while True:
    try:
        os.system(matlabCommandStr)
    except Exception as e:
        print(e)
        error_flag = 1
        break

I know that if I use Matlab toolbox in Python, following code will work:

import matlab.engine
while True:
    try:
        eng = matlab.engine.start_matlab()
        ret = eng.yyy()
    except Exception as e:
        print(e)
        error_flag = 1
        break

But I need to work with the command line because of matlab.engine limitation and the toolbox that I am preparing is already complicated enough to change to matlab.engine, so I want to keep using os.system(matlabCommandStr). I'd appreciate if someone can help with this.

CodePudding user response:

Using the hint from @CrisLuengo's answer, I used -batch instead of -nodisplay -r and then when there is an error status = 256 and if no error happens then status = 0. I used this as a flag to detect errors. The following code helped me to solve this problem:

import os
path_to_mfile = '/Users/folder/yyy'
matlabCommandStr = 'matlab -batch "run(\'{}\'); quit" '.format(path_to_mfile)

while True:
    status = os.system(matlabCommandStr)
    if status == 256:
        error_flag = 1

I will integrate this into my multiprocess tool. If there were further problems, I'll update here.

  • Related