如何从主实时脚本获取子实时脚本的LiveEditorEvaluationHelper文件名?
MATLAB实时脚本调用子脚本时无法获取子脚本的临时评估文件名
问题复现(最小可复现示例)
我有两个实时脚本main.mlx和sub.mlx:
main.mlx代码:
dbstack().file sub
sub.mlx代码:
dbstack().file
现象:
- 手动运行
sub.mlx时,dbstack().file返回的临时文件名(格式为LiveEditorEvaluationHelper(随机数).m)和运行main.mlx时的不同,符合预期; - 但通过
main.mlx调用sub.mlx时,两次dbstack().file返回的文件名完全相同,无法区分主脚本和子脚本的临时文件。
我需要从main.mlx中获取sub.mlx对应的LiveEditorEvaluationHelper(随机数).m文件名,但该文件名随MATLAB重启变化,无法通过预存变量解决。matlab.desktop.editor.getActiveFilename也无效,因为此时活动文件是main.mlx。推测直接调用sub.mlx不会将其加入调用栈(dbstack),但暂无解决思路。
背景与核心需求
出于教学目的,我用实时脚本编写物理模拟代码,按模块拆分为多个子脚本并附带原理说明。部分子脚本中的函数需要被主脚本调用,但直接执行sub无法将子脚本的函数加载到工作区,因此我编写了saveFunction函数,用于动态导出子脚本中的函数为.m文件:
saveFunction.m代码:
function saveFunction(functionName) stack = dbstack; % Get the current script filename and line number scriptName = stack(2).file; % The file where the function is called % Open the script file fid = fopen(scriptName, 'r'); if fid == -1 error('Cannot open the file: %s', scriptName); end % Initialize variables to track lines currentLine = stack(2).line; % The line where the function is called linesToSave = {}; foundFunction = false; % Read the file and move upwards, starting just above the current line lineNumber = currentLine - 1; while lineNumber > 0 % Read the current line lineNum = 1; fseek(fid, 0, 'bof'); % Reset fgetl while lineNum < lineNumber fgetl(fid); % Skip the lines until the target line lineNum = lineNum + 1; end tline = fgetl(fid); % Check if we found a 'function' keyword in this line if contains(tline, 'function') foundFunction = true; linesToSave{end+1} = tline; % Save the line with 'function' break; % Stop since the full function definition has been found end % Add the line to the linesToSave list linesToSave{end+1} = tline; % Decrease the line number to move upwards lineNumber = lineNumber - 1; end % Close the file fclose(fid); % If no function was found, raise an error if ~foundFunction error('No function definition found in the script before the call.'); end % Save the collected lines to a text file with the functionName fileID = fopen(['Functions/', functionName, '.m'], 'w'); if fileID == -1 error('Cannot create the file: %s.m', functionName); end % Write the lines to the text file for i = length(linesToSave):-1:1 fprintf(fileID, '%s\n', linesToSave{i}); end % Close the output file fclose(fileID); disp(['Code saved successfully as Functions/', functionName, '.m']); end
子脚本中的调用方式(sub.mlx):
% a function in sub.mlx function a = myFunction(b, c) a = b + c; end saveFunction('myFunction');
问题:
手动运行sub.mlx时,saveFunction可以正常找到并导出函数;但通过main.mlx调用sub.mlx时,dbstack无法获取sub.mlx的临时文件路径,导致scriptName和currentLine错误指向main.mlx,函数完全失效。
需要找到一种可靠的方式,在main.mlx调用sub.mlx时,让saveFunction能够正确获取sub.mlx的临时文件信息,或者找到其他方法实现子脚本函数的动态导出。
内容的提问来源于stack exchange,提问作者MathiasD
相关产品推荐
相关产品推荐

