Get path from running script
1,113 ビュー (過去 30 日間)
古いコメントを表示
Greetings!
I know that this is a bit hackneyed, but I couldn't get a working solution.
I run a script (not function) saved as m-file. Now I want to get path to the m-file from inside the script.
Widely suggested mfilename('fullpath') returns nothing, because it should be called from a function (but not from script).
Can you suggest a viable solution please?
Thank you!
0 件のコメント
回答 (12 件)
Sean Collins
2019 年 10 月 7 日
編集済み: Sean Collins
2021 年 9 月 10 日
I was trying to solve the same problem, and I discovered an answer based on an answer from Jacob Halbrooks to another related question (see this question and answer). Inserting the following into my script worked for me, even when running the script with the "Run Section" tool or when highlighting a piece of the code, right clicking, and selecting "Evaluate Selection". This assumes that the script that you are executing will be the active file in the editor window, but I believe that should be the case.
As a note, this solution will work for a script that you are currently executing, but would not be appropriate for use inside a function to get the name of that function. In that case, it could give unexpected results, as it should return the path to the currently active file in the editor window, regardless of which function executed the command.
I hope that helps, or at least helps someone else running into the same challenge in the future!
filePath = matlab.desktop.editor.getActiveFilename;
fprintf('%s\n',filePath);
% note - I edited the variable name from "path" to "filePath" based on
% Image Analyst's comment. Thanks for the heads up on the naming conflict!
10 件のコメント
Image Analyst
2022 年 11 月 1 日
@Yongqi Shi, try just typing it in and see what auto-completion brings up.
Yair Altman
2022 年 11 月 1 日
編集済み: Yair Altman
2022 年 11 月 1 日
I just came across this thread due to IA's mention... FWIW, I added an answer to the OP's question that does not rely on running the script from within the editor, namely using the dbstack function:
stk = dbstack; filepath = which(stk(1).file)
Ming Li
2022 年 11 月 24 日
編集済み: Ming Li
2022 年 11 月 24 日
mfilePath = mfilename('fullpath');
if contains(mfilePath,'LiveEditorEvaluationHelper')
mfilePath = matlab.desktop.editor.getActiveFilename;
end
disp(mfilePath);
This code will give the right result no matter you run the code by "Alt+Enter" or run the whole mfile directly, even the mfile is called by another mfile.
the cyclist
2013 年 7 月 4 日
編集済み: the cyclist
2013 年 7 月 4 日
mfilename('fullpath')
actually works for me, even inside a script. However, you could try this instead:
[pwd,'/',mfilename]
3 件のコメント
Image Analyst
2013 年 7 月 4 日
No, you don't. Windows PCs will work just fine with slashes in either direction.
Wouter
2019 年 5 月 31 日
note:
mfilename()
this only returns the path of your script if you press F5 (run entire script). If you use CTRL + enter to run a section, it will not work. (then it shows some temporary location)
Image Analyst
2013 年 7 月 4 日
Andrey, you're getting confused between the command and the function. They behave differently so, granted, it can be confusing. When you don't put parentheses around a command's arguments, it acts like the arguments are the actual filename, not the contents of the variable with that name. When you use parentheses, it's using the function, not the command and will replace the variable name with the contents of it.
For example
>> load mymatfile
will try to load a file called mymatfile - I think it may add .mat extension though by default so it really loads mymatfile.mat. If you do
>> load(mymatfile)
it will look at the variable called mymatfile and see if it's the name of a file and try to load it. For example
>>mymatfile = 'abc.mat';
>> s = load(mymatfile);
will load abc.mat, not mymatfile.mat. The only difference is the parentheses. Note that if you didn't assign mymatfile to a string, you'd get an error.
Now look at this script, test.m:
mfilename
mfilename('fullpath')
which(mfilename)
which('mfilename')
What do you think it will return? It returns this:
ans =
test
ans =
D:\Matlab\work\Tests\test
D:\Matlab\work\Tests\test.m
built-in (C:\Program Files\MATLAB\R2013a\toolbox\matlab\lang\mfilename)
mfilename is a function. The first time I call it, it returns the base filename - no folder and no extension. When I call "mfilename('fullpath')" it returns almost the full path - it returns the folder, base filename, but no extension.
Now, when I call which(mfilename), that is the same as issuing the command "which('test')" and that will tell MATLAB to return the full filename of the script I'm running. It's interesting to note that it returns more of the full filename than mfilename('fullpath') because it includes the extension.
Now, finally when I call which('mfilename') - with single quotes around mfilename - it considers mfilename literally as the name of an m-file that you want information on (the full path and name, including any other files with similar name in other folders on the search path). So it's really saying which('mfilename.m') which means "tell me where the function named mfilename.m lives. And since mfilename is actually a function that is contained in an m-file, it returns built-in (C:\Program Files\MATLAB\R2013a\toolbox\matlab\lang\mfilename). This is the full path and name of the m-file where the mfilename function is contained.
I hope that explains things better and makes it more understandable.
Anyone know where this command/function distinction/difference is explained in the help?
3 件のコメント
Image Analyst
2013 年 9 月 3 日
I have no idea. I just did it again and got what I said, not blanks like you got.
William Haselden
2018 年 9 月 7 日
Really late so just for people checking this tread out later but you're probably running it from matlab's command window. Put the mfilename('fullpath') command in a script, run the script, and it should give you that script's location.
Roberto Osorio
2015 年 4 月 15 日
This reply is very late, but I hope it can help users who get to this thread by searching. Experimenting with mfilename in scripts, I observed that the behavior that Andrey Kazak reports, i.e., empty strings returned from mfilename, occurs when you run the script manually (highlighting + Right-Click Evaluate or clicking Run Section in the Toolstrip). This is equivalent to typing the command in the Command Window.
To get the normal documented behavior of mfilename, you need to run the script either from a batch job or by clicking the Run button in the Toolstrip.
Joao Pereira
2021 年 7 月 5 日
I just tested this with MATLAB R2021a and
mfilename('fullpath')
worked for me both from a script and a function. It might be that this behaviour changed recently, let's not forget we can define functions inside scripts now.
0 件のコメント
Yair Altman
2022 年 11 月 1 日
mfilename('fullpath') does indeed return the full path to the currently-running script file, at least on the latest Matlab release (R2022b).
On older Matlab releases where mfilename('fullpath') doesn't work, you can use this alternative:
stk = dbstack; filepath = which(stk(1).file)
1 件のコメント
hassan
2022 年 11 月 15 日
one can use dbstack with '-completenames' argument to avoid relying on which command in case where the file is not seen in Matlab path.
This would be :
stk = dbstack('-completenames'); filepath = stk(1).file;
Andrey Kazak
2013 年 7 月 4 日
2 件のコメント
the cyclist
2013 年 7 月 4 日
This "answer" would be better placed as a comment on the relevant answer.
the cyclist
2013 年 7 月 4 日
編集済み: the cyclist
2013 年 7 月 4 日
Try
which(mfilename)
This potentially has some foibles, too, if you have same-named scripts in multiple directories.
5 件のコメント
Andrey Kazak
2017 年 8 月 18 日
1 件のコメント
Image Analyst
2017 年 8 月 18 日
Are you sure you're not doing it from the command line? I just tried it and if you do it from the command window, it will give you empty string but if you do it from a script m-file, it gives you the actual m-file name.
Please use the snipping tool to save a screenshot and post it here with the green and brown frame icon:
Martin Bubel
2019 年 2 月 19 日
編集済み: Martin Bubel
2019 年 4 月 9 日
Hi,
I usually use the following workaround, since mfilename('fullpath') did not work for me as well.
When you start a MatLab-Script, you have to change directory to the script you want to execute. While in that specific directory, you can use the following:
directory_content = dir; % contains everything of the current directory
exe_path = directory_content(1).folder; % returns the path that is currently open
The above mentioned workaround however does not work if the script called from any other directory than it's location (for example if it has been added to the searchpath or if it has been imported).
I hope this helps!
1 件のコメント
Jeffrey Daniels
2020 年 4 月 23 日
This question assumes you don't already know which directory to change to.
You have just recreated the existing Matlab function pwd.m.
David Weigt
2022 年 6 月 9 日
編集済み: David Weigt
2022 年 6 月 9 日
cd(erase(mfilename('fullpath'), mfilename('class'))) %Change the direction
erase(mfilename('fullpath'), mfilename('class')) %Gives you only the path of the skript
workingpath = erase(mfilename('fullpath'), mfilename('class')) %You can save it in a value
This is the easiest way, beacuse pwd gives you only the current path not the script path.
I dont know what do you mean with
Widely suggested mfilename('fullpath') returns nothing, because it should be called from a function (but not from script).
But I think this is the easiest solution.
0 件のコメント
参考
カテゴリ
Help Center および File Exchange で Entering Commands についてさらに検索
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!