Get path from running script

1,266 次查看(过去 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.

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?

请先登录,再进行评论。


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 中查找有关 Debugging and Analysis 的更多信息

Community Treasure Hunt

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

Start Hunting!

Translated by