【问题标题】:Is it possible to check if a given Matlab script is run by itself or called by another script?是否可以检查给定的 Matlab 脚本是自己运行还是被另一个脚本调用?
【发布时间】:2016-02-12 09:24:22
【问题描述】:

我有一个 Matlab 脚本 A,它既可以自己运行,也可以由另一个脚本调用。我想在脚本 A 中输入一个if 语句,检查脚本是自己运行还是被另一个脚本调用。我该如何检查?

【问题讨论】:

    标签: matlab if-statement call


    【解决方案1】:

    您应该查看dbstack

    dbstack 显示导致当前断点的函数调用的行号和文件名,按执行顺序列出。显示首先列出最近执行的函数调用(当前断点发生处)的行号,然后是它的调用函数,然后是它的调用函数,依此类推。

    还有:

    除了在调试时使用 dbstack,您还可以在调试上下文之外的 MATLAB 代码文件中使用 dbstack。在这种情况下,获取和分析有关当前文件堆栈的信息。例如,要获取调用文件的名称,请在被调用文件中使用带有输出参数的 dbstack。例如:

    st=dbstack;

    以下内容来自File Exchange 上发布的iscaller 功能。

    function valOut=iscaller(varargin)
    stack=dbstack;
    %stack(1).name is this function
    %stack(2).name is the called function
    %stack(3).name is the caller function
    if length(stack)>=3
        callerFunction=stack(3).name;
    else
        callerFunction='';
    end
    if nargin==0
        valOut=callerFunction;
    elseif iscellstr(varargin)
        valOut=ismember(callerFunction,varargin);
    else
        error('All input arguments must be a string.')
    end    
    end
    

    此方法的功劳归于Eduard van der Zwan

    【讨论】:

      【解决方案2】:

      您可以使用函数dbstack - Function call stack

      让我们将其添加到脚本文件的开头,称之为“dbstack_test.m”:

      % beginning of script file
      callstack = dbstack('-completenames');
      if( isstruct( callstack ) && numel( callstack ) >= 1 )
          callstack_mostrecent = callstack(end); % first function call is last
          current_file = mfilename('fullpath'); % get name of current script file
          current_file = [current_file '.m']; % add filename extension '.m'
      
          if( strcmp( callstack_mostrecent.file, current_file ) )
              display('Called from itself');
          else
              display( ['Called from somewhere else: ' callstack_mostrecent.file ] );
          end
      else
          warning 'No function call stack available';
      end
      

      添加另一个名为“dbstack_caller_test”的脚本来调用您的脚本:

      run dbstack_test
      

      现在,当您从控制台运行 dbstack_test 或单击 MATLAB 编辑器中的绿色三角形时:

      >> dbstack_test
      Called from itself
      

      当你调用它从dbstack_caller_test运行时

      >> dbstack_caller_test
      Called from somewhere else: /home/matthias/MATLAB/dbstack_caller_test.m
      

      当您在 MATLAB 的编辑器中使用“运行当前部分”(Ctrl+Return)调用它时,您会得到

      Warning: No function call stack available 
      

      当然,您可以根据需要从调用堆栈中使用的级别来修改代码。

      正如文档中已经提到的:“除了在调试时使用 dbstack,您还可以在调试上下文之外的 MATLAB 代码文件中使用 dbstack。”

      【讨论】:

        猜你喜欢
        • 2020-09-23
        • 2012-02-10
        • 1970-01-01
        • 2019-09-03
        • 2014-06-26
        • 1970-01-01
        • 1970-01-01
        • 2019-07-04
        • 1970-01-01
        相关资源
        最近更新 更多