Home > Blockchain >  How to get Matlab error message when running a Matlab script from Python
How to get Matlab error message when running a Matlab script from Python

Time:12-20

I am running a Matlab script through Python. For some reasons, I am running it using os.system('matlab -batch "my_script;"') in Python. Assume there is an error in the Matlab script. This error will be printed on the terminal window as Matlab work space, but I want to catch the error message in python level and use it for other purposes (e.g. email it out or save it to a txt file ...). I'd appreciate it if you can help me with this.

Note, for a reason, I can't use Matlab engine package in Python, so I am using system command.

CodePudding user response:

I found the solution. Answering my question in case someone had a similar problem:

In you Matlab script do this:

if exist('error_message', 'file')
   delete('error_message'); 
end
try
   your_script_or_any_operation; 
catch ME
   diary('error_message')
   disp(ME.message);
end

This will write the error in the error_message file.

CodePudding user response:

You should use subprocess.run instead of os.system. You will be able to capture stderr (the stream that MATLAB writes error messages to when you use -batch) as a string. This will avoid the need for files to capture error messages.

  • Related