Get path from running script

조회 수: 1,007 (최근 30일)
Andrey Kazak
Andrey Kazak 2013년 7월 4일
댓글: Johannes 2023년 7월 4일
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!

답변 (12개)

Sean Collins
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
Image Analyst 2022년 11월 1일
@Yongqi Shi, try just typing it in and see what auto-completion brings up.
You'll also like to look at @Yair Altman's site: Undocumented Matlab
Yair Altman
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
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.
  댓글 수: 1
Johannes
Johannes 2023년 7월 4일
Very good, works!

댓글을 달려면 로그인하십시오.


the cyclist
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
Image Analyst 2013년 7월 4일
No, you don't. Windows PCs will work just fine with slashes in either direction.
Wouter
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
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
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
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
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.
  댓글 수: 2
Andrey Kazak
Andrey Kazak 2015년 4월 16일
Thank you for confirming. I create a script in R2015a and save it somewhere. Ctrl+Enter fails. Green Run button at the Toolstrip works.
Is this a bug or a feature?
Image Analyst
Image Analyst 2015년 4월 16일

Or this:

댓글을 달려면 로그인하십시오.


Joao Pereira
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.

Yair Altman
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
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
Andrey Kazak 2013년 7월 4일
mfilename('fullpath') returns empty string on R0213a at Windows 7. [pwd,'/',mfilename] is not exactly what I need, because if your pwd is different from location of the script it will return wrong path.
  댓글 수: 2
the cyclist
the cyclist 2013년 7월 4일
This "answer" would be better placed as a comment on the relevant answer.
Zhengyi
Zhengyi 2018년 1월 22일
편집: Zhengyi 2018년 1월 22일
The documentation says:
When called from the command line, mfilename returns an empty character vector.

댓글을 달려면 로그인하십시오.


the cyclist
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
Andrey Kazak 2013년 7월 4일
>> which mfilename
built-in (C:\Program Files\MATLAB\R2013a\toolbox\matlab\lang\mfilename)
But the script executes exactly as if you typed all the code of script from command window. Are you sure you're running a script, but not a function?
the cyclist
the cyclist 2013년 7월 4일
Yes, I am sure I am in a script.

댓글을 달려면 로그인하십시오.


Andrey Kazak
Andrey Kazak 2017년 8월 18일
Try to do the same in R2017a on Windows, but get empty strings even if I push green Run button.
Can you confirm this?
  댓글 수: 1
Image Analyst
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
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
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
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.

카테고리

Help CenterFile Exchange에서 Entering Commands에 대해 자세히 알아보기

Community Treasure Hunt

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

Start Hunting!

Translated by