Automatically add an opened live script's directory to the search path for the current session

2 次查看(过去 30 天)

Is there a way to automatically add an opened Live Script's directory to the search path for the session?

Desired behavior:

  1. Open file browser, navigate to directory where Live Script resides
  2. Double click on Live Script, which opens up MATLAB
  3. Either: (a) the directory where the Live Script file lives is listed as the "current directory" or (b) the directory where the Live Script file lives is added to the search path for the current session.

Use case:

I'll be sharing Live Scripts demoing concepts with my students. Some of these will load .mat files that I will also share with them. If the students just download the attachments from my e-mail into some random directory and run it, the Live Script won't be able to find the .mat files to load.

Comments:

For normal scripts (.m files), I can force change the directory with

    cd(fileparts(which(mfilename)));

But running mfilename on a Live Script gives not the expected answer:

    ans = 'LiveEditorEvaluationHelperE976215442'

and I would appreciate a Live Script specific answer.

回答(1 个)

Gleb Medikov
Gleb Medikov 2021-12-2
编辑:Gleb Medikov 2021-12-2
Hello. If I understood you correctly, the main problem is that livescript does not understand its new work directory and does not download any .m functions from there. I wan to share my solution to this problem. Just paste this code in the begining of livescript. It will solve problems with new work directory and information in current folder window.
filePath = matlab.desktop.editor.getActiveFilename;
for i = length(filePath):-1:1
if filePath(i) == '\'
slash(i,1) = 1;
end
end
filePath = filePath(1:length(slash) ); cd (filePath);
  2 个评论
Walter Roberson
Walter Roberson 2021-12-2
filePath = matlab.desktop.editor.getActiveFilename;
filePath = fileparts(filePath);
cd(filePath)
This does, however, depend upon the idea that the activeFileFilename is the same as the executing file, which might not be the case if one file is invoking another file.
Walter Roberson
Walter Roberson 2022-9-12
My tests show that if you invoke a Live Script from the editor prompt, then inside it, mfilename will refer to a file in tempdir() that MATLAB extracted the MATLAB portion of the livescript into.
However, my tests show that if you invoke a Live Script this way and the Live Script has code that calls a different Live Script, then inside the second live script, mfilename() will give you the correct full path to the second live script (except without the .m extension). So mfilename() is only messed up for the first layer of Livescript, not for live scripts called from the first layer.

请先登录,再进行评论。

类别

Help CenterFile Exchange 中查找有关 File Operations 的更多信息

产品


版本

R2018a

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by