【问题标题】:How to get Matlab error message when running a Matlab script from Python从 Python 运行 Matlab 脚本时如何获取 Matlab 错误消息
【发布时间】:2022-01-21 03:00:34
【问题描述】:

我正在通过 Python 运行 Matlab 脚本。由于某些原因,我在 Python 中使用 os.system('matlab -batch "my_script;"') 运行它。假设 Matlab 脚本中存在错误。此错误将作为 Matlab 工作空间打印在终端窗口上,但我想在 python 级别捕获错误消息并将其用于其他目的(例如通过电子邮件发送或将其保存到 txt 文件......)。如果您能帮我解决这个问题,我将不胜感激。

注意,由于某种原因,我不能在 Python 中使用 Matlab 引擎包,所以我使用的是系统命令。

【问题讨论】:

    标签: python matlab error-handling


    【解决方案1】:

    我找到了解决方案。如果有人遇到类似问题,请回答我的问题:

    在你的 Matlab 脚本中这样做:

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

    这会将错误写入error_message 文件中。

    【讨论】:

      【解决方案2】:

      您应该使用subprocess.run 而不是os.system。您将能够捕获stderr(当您使用-batch 时,MATLAB 将错误消息写入的流)作为字符串。这将避免需要文件来捕获错误消息。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2014-07-22
        • 2021-12-29
        • 2019-01-08
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多