当 运行 来自 Python 的 Matlab 脚本时检测到错误并在 Python 中引发标志
Detect an error and raise flag in Python when running an Matlab script from Python
我有一个 Matlab 脚本,我是 运行从 Python 编译它的。我想检测我的 Matlab 脚本中发生的任何错误,并在 Python(例如 e = "error message from Matlab"
和 print(e)
或 if error_in_matlab: e=1
中发出一个标志。这是我 运行 我的 yyy.m
matlab 脚本的简化代码:
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
我知道如果我在 Python 中使用 Matlab 工具箱,下面的代码将起作用:
import matlab.engine
while True:
try:
eng = matlab.engine.start_matlab()
ret = eng.yyy()
except Exception as e:
print(e)
error_flag = 1
break
但由于matlab.engine
的限制,我需要使用命令行,而且我正在准备的工具箱已经很复杂,可以更改为matlab.engine
,所以我想继续使用os.system(matlabCommandStr)
。如果有人可以提供帮助,我将不胜感激。
使用@CrisLuengo 回答中的提示,我使用 -batch
而不是 -nodisplay -r
然后当出现错误时 status = 256
如果没有错误发生则 status = 0
.我用它作为检测错误的标志。以下代码帮助我解决了这个问题:
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
我会将其集成到我的多进程工具中。如果还有问题,我会在这里更新。
我有一个 Matlab 脚本,我是 运行从 Python 编译它的。我想检测我的 Matlab 脚本中发生的任何错误,并在 Python(例如 e = "error message from Matlab"
和 print(e)
或 if error_in_matlab: e=1
中发出一个标志。这是我 运行 我的 yyy.m
matlab 脚本的简化代码:
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
我知道如果我在 Python 中使用 Matlab 工具箱,下面的代码将起作用:
import matlab.engine
while True:
try:
eng = matlab.engine.start_matlab()
ret = eng.yyy()
except Exception as e:
print(e)
error_flag = 1
break
但由于matlab.engine
的限制,我需要使用命令行,而且我正在准备的工具箱已经很复杂,可以更改为matlab.engine
,所以我想继续使用os.system(matlabCommandStr)
。如果有人可以提供帮助,我将不胜感激。
使用@CrisLuengo 回答中的提示,我使用 -batch
而不是 -nodisplay -r
然后当出现错误时 status = 256
如果没有错误发生则 status = 0
.我用它作为检测错误的标志。以下代码帮助我解决了这个问题:
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
我会将其集成到我的多进程工具中。如果还有问题,我会在这里更新。