运行 来自 Matlab 命令行的特定单元格部分?

Run particular cell section from command line in Matlab?

我在脚本中手动循环遍历 Matlab 中的各种单元格(我们称之为 foo.m):

%%
%Code for cell 1

%%
%Code for cell 2

在 Matlab 的命令行中,我希望能够有选择地 运行 单元格 2 中的代码。The documentation 只有关于如何以交互方式执行此操作的说明(例如,将光标在适当的单元格中,然后等等等等)。我想要命令行的东西,所以我可以做一些像 foo.runCell(1) 到 运行 上面单元格 1 中的代码。

如果没有办法,我就把单元格拆分成单独的scripts/functions。这不太方便,因为我处于 'grind out prototype very quickly' 编码模式,所以现在希望所有内容都在一个文件中。

这是我的丑陋代码,可以满足您的要求。

尽管我尽了最大的努力,但我无法找到让它工作的方法 "properly"(即没有模拟按键)。我希望这将有助于其他人尝试找到正确的方法。无论如何,这里是:

runCodeSectionInFile.m:

function runCodeSectionInFile(scriptFullPath,sectionNum)
%// TIP: You can use "which('scriptName')" to obtain the full path of a 
%// script on your MATLAB path.
%%% // Temporary Workaround
import java.awt.Robot;   %// part of temporary workaround
import java.awt.event.*; %// part of temporary workaround
RoboKey = Robot;         %// part of temporary workaround
RoboKey.setAutoDelay(10);%// part of temporary workaround
%% // Test if the needed components are available (optional)
if ~matlab.desktop.editor.isEditorAvailable || ...
   ~com.mathworks.mde.editor.codepad.Codepad.isCodepadEnabled
    error('MATLAB editor is N\A');
end
%% // Open and\or switch to the script file
%// Test if script is opened:
if ~matlab.desktop.editor.isOpen(scriptFullPath) 
    scriptDoc = matlab.desktop.editor.openDocument(scriptFullPath);
else %// in case the script is open, get a handle to it, and save it:
    scriptDoc = matlab.desktop.editor.findOpenDocument(scriptFullPath);
    %// Save the script before running (optional):
    scriptDoc.save;
end
scriptDoc.goToLine(0); %// Position the cursor at the beginning of the file
                       %// NOTE1: - uses zero based indexing!
jEd = com.mathworks.mlservices.MLEditorServices.getEditorApplication ...
        .openEditorForExistingFile(java.io.File(scriptFullPath));
jEd.getTextComponent.grabFocus; drawnow; %// part of temp fix
%// NOTE2: most of the above can be replaced with:
%//   EDITOROBJ = matlab.desktop.editor.openAndGoToLine(FILENAME,LINENUM);
%% // Get the Codepad and the LineManager handles:
jCm = com.mathworks.mde.editor.codepad.CodepadActionManager ...
                   .getCodepadActionManager(jEd);
jCp = jEd.getProperty('Codepad');
jLm = jCp.getLineManager(jEd.getTextComponent,jCm);
%% // Advance to the desired section
jAc = com.mathworks.mde.editor.codepad.CodepadAction.CODEPAD_NEXT_CELL;
                                           %// 'next-cell' Action

for ind1=1:sectionNum-1 %// click "advance" several times
    %// <somehowExecute(jAc) OR jCp.nextCell() >    
    RoboKey.keyPress(KeyEvent.VK_CONTROL); %// part of temporary workaround
    RoboKey.keyPress(KeyEvent.VK_DOWN);    %// part of temporary workaround
end
RoboKey.keyRelease(KeyEvent.VK_DOWN);      %// part of temporary workaround
RoboKey.keyRelease(KeyEvent.VK_CONTROL);   %// part of temporary workaround
%% Execute section - equivalent to clicking "Run Section" once

jAc = com.mathworks.mde.editor.codepad.CodepadAction.CODEPAD_EVALUATE_CELL; 
                                                 %// 'eval-cell' Action
%// <somehowExecute(jAc); OR jCp.evalCurrentCell(true) >    
RoboKey.keyPress(KeyEvent.VK_CONTROL); %// part of temporary workaround
RoboKey.keyPress(KeyEvent.VK_ENTER);   %// part of temporary workaround
RoboKey.keyRelease(KeyEvent.VK_CONTROL);   %// part of temporary workaround
%% // Close the file (optional)
jEd.close;
%% // Return focus to the command line:
com.mathworks.mde.cmdwin.CmdWin.getInstance.grabFocus;

testScript.m:

%% // This is code block one
disp('This is section one');
%% // This is code block two
disp('This is section two');
%% // This is code block three
disp('This is section three');

对于 运行 演示,只需将两个文件放在同一个文件夹中,确保它在您的路径(或 cd)上,然后执行 runCodeSectionInFile(which('testScript.m'),1)。结果如下:

>> runCodeSectionInFile(which('testScript.m'),1)
This is section one
>> runCodeSectionInFile(which('testScript.m'),2)
This is section two
>> runCodeSectionInFile(which('testScript.m'),3)
This is section three

如果你得到 NPE,你可能还需要将 RoboKey.setAutoDelay(10); 调整到更大的数字。

来源:

  1. A long-gone MATLAB blog post.

  2. Some old question I posted and its answers.

P.S。 我在 2014b 上写了这篇文章。其他(旧)版本可能需要调整...

编辑 1:

通过找到 Codepad 对象及其 TaggedLineManager 的句柄,我设法解开了这个谜题的另一块。当前的问题是大多数 Codepad 方法在 EDT 上必须是 运行(类似于 "UI thread",即源自与界面的交互)。

Dev-iL 使用 java 等提供了一个很好的答案...我将在此处提供一个不使用 java 或编辑器,但读取文件并在请求时评估语句。

为了使其工作,它有一个先决条件,即文件已保存(我很欣赏这不是 运行ning cells/codeBlocks 交互的先决条件) .

无论如何,我认为这是一个 "quirky" 问题,我想我会添加一个答案。

这是我的脚本 (cellScript.m),其中包含代码块(请注意,我在“%%”之后为每个块指定了​​一个名称:

%Note: for this method your NOT allowed to put comments at the end of lines
%% cellA
disp ( 'running cell A' ); 
disp ( 'finished cell A' );
%% cellB
disp ( 'running cell B' );
disp ( 'finished cell B' );
%% cellC
disp ( 'running cell C' );
for ii=1:100
  aa(ii) = randi(1);
end
% cells can have comments
disp ( 'past 1st coment' );
   % cells comments can be indented
disp ( 'past indented comment' );

  %{
   block 
   comment
  %}
disp ( 'past block comment' );

% cells can have comments
% multiple lines of comments
  % not lined up
%
%and empty

disp ( 'past multiple lines of comments' );

disp ( 'finished cell C' );
%% cellD
disp ( 'running cell D' );

disp ( 'finished cell D' );
%% cellE
disp ( 'running cell E' );
disp ( 'finished cell E' );

我创建了一个 class 来完成请求的工作(我称之为 cellRunner.m )

classdef cellRunner < handle
  properties ( SetAccess = private )
    fileName
    fileInfo
    cellInfo
    cellNames = {};
  end
  methods 
    function obj = cellRunner ( file ) % constructor
      if nargin == 0                        
        obj.fileName = 'cellScript.m';      % default file for testing
      else
        obj.fileName = file;                % store user file
      end
      obj.parseFile();                      % read the file into memory
    end
    function obj = parseFile ( obj )
      if ~isempty ( obj.fileInfo )                        % on parsing check to see if its been parsed before
        if isequal ( obj.fileInfo, dir ( obj.fileName ) ) % Check date stamp (has cell file been modified
%           disp ( 'file not changed - reading skipped' );  % if not skip
%           reading 
          return
        end
      end
      obj.fileInfo = dir ( obj.fileName );                % store file info
      fid = fopen ( obj.fileName );                       % open file for reading
      if fid ~= -1
        index = 0;                                        % this is the index of each cell
        inCell = false;                                   % has it found a cell to start reading
        lines = cell(0);                                  
        while ( true )
          line = fgetl ( fid );                           % read the line in the file
          if line == -1; break; end                       % check for the end of the file
          sLine = strtrim ( line );                       % trim any white space
          if length ( sLine ) > 2 && strcmp ( sLine(1:2), '%%' ) % check to see if its the start of a cell
            if index > 0                                  % Store the last cell data                
              obj.cellInfo{index} = lines;                % in class to run when required
            end
            index = index + 1;                            % increment the index
            obj.cellNames{index} = strtrim ( sLine(3:end) ); % save the name of the cell
            lines = cell(0);                              % re-initialise the lines var
            inCell = true;                                % the start of the cells have been found
          elseif inCell                                   % if reading a cell array
            lines{end+1} = line;                          % add each line to the lines var
          end          
        end
        if index > 0                                      % make sure and save the last cell when finished reading
          obj.cellInfo{index} = lines;
        end
        fclose ( fid );
      else
        error ( 'cellRunner:fileError', 'unable to read file' );
      end
    end
    function obj = runCell ( obj, arg )
      % obj.runCell ( 'cellName' );
      % obj.runCell ( index );
      obj.parseFile();                                    % check that the file hasn't been changed
      if ischar ( arg )                                   % if user provided a char then search for it
        index = strcmp ( arg, obj.cellNames );            % find the index
        if ~any ( index )                                 % check it was found
          error ( 'cellRunner:notFound', '%s not found', arg ); 
        end
      else
        index = arg;                                      % if index is an integer (not checked - assumed if not char)
        if index < 1 || index > length ( obj.cellInfo )   % check integer is valid
          error ( 'cellRunner:notFound', 'Index %d not found', arg );
        end
      end
      commands = obj.cellInfo{index}{1};                  % start to build the command to execute.
      inBlock = false;
      for ii=2:length(obj.cellInfo{index})                % loop around - ignoring any commented lines.
        nextLine = strtrim ( obj.cellInfo{index}{ii} ); 
        if inBlock
          if length ( nextLine ) == 2 && strcmp ( nextLine, '%}' );
            inBlock = false;
          end
          continue
        end
        if length ( nextLine ) == 2 && strcmp ( nextLine, '%{' );
          inBlock = true;
          continue
        end
        if length ( nextLine ) >= 1 && strcmp ( nextLine(1), '%' )
          continue;
        end
        commands = sprintf ( '%s;%s', commands, obj.cellInfo{index}{ii} ); % build a parge string to eval
      end
      evalin('base',commands);                            % eval the expression in the base workspace.
    end
  end
end

然后使用代码如下:

obj.cellRunner();
% Individual cells can be run in two ways:

% By providing the name of the cell (the string after the %%)
obj.runCell ( 'cellC' );
% By providing the index
obj.runCell ( 3 );

注意 回想一下,必须保存文件才能工作。

样本运行:

whos
obj = cellRunner ( 'cellScript.m' );
obj.runCell ( 'cellC' );
running cell C
past 1st coment
past indented comment
past block comment
past multiple lines of comments
finished cell C
whos
  Name      Size             Bytes  Class         Attributes

  aa        1x100              800  double                  
  ans       1x1                112  cellRunner              
  ii        1x1                  8  double                  
  obj       1x1                112  cellRunner              

注1 - 为什么handle class? 我继承自handle class 因为我只想要一份已读取的文件数据- 有关何时使用 value/handle classes.

的出色概述,请参阅 answer 1 in this question

为了使用命令行运行文件中的特定部分,您可以使用

echodemo(filename, index of section)

MATLAB documentation