以编程方式区分脚本和函数 [英] Distinguish between scripts and functions programmatically
问题描述
如果我试图将一个参数传递给脚本,我得到尝试执行SCRIPT somescript作为函数:
。有没有办法检测到这一点,而不尝试执行它?
更新:由于@ Craq指出,在发布这个问题后不久,有一篇关于MATLAB Central的文章: http://blogs.mathworks.com/loren/2013/08/26/what-kind-of-matlab-file-is-this/
没有找到干净的解决方案,但可以使用 try-catch
(如@Ilya建议)和
nargin
编辑 - 使用函数
来避免一些命名冲突;使用 exists
来进一步对输入进行分类(例如MEX文件)
函数is_script = is_a_script(varargin)
%is_a_script(varargin)返回以下内容之一:
%1:如果输入是脚本
%0:如果输入是函数
%-1:如果输入既不是函数也不是脚本。
is_script = 0;
switch(exists(varargin {1}))
case 2
%如果输入不是MEX或DLL或MDL或内建或P文件或变量或类或文件夹,
%then exists()返回2
尝试
nargin(varargin {1});
catch err
%如果nargin引发错误并且错误消息与脚本的特定错误消息不匹配,则输入既不是脚本也不是函数。
if(strcmp(err.message,sprintf('%s is a script。',varargin {1})))
is_script = 1;
else
is_script = -1;
end
end
case {3,4,5,6}%MEX或DLL文件,MDL文件,内置P文件
%我不是熟悉DLL文件/ MDL文件/ P文件。我假设他们都被视为功能。
is_script = 0;
否则%Variable,Folder,Class或其他情况
is_script = -1;
end
Given a file name, how can I programmatically distinguish between scripts and functions in MATLAB?
If I attempt to pass an argument to a script, I get Attempt to execute SCRIPT somescript as a function:
. Is there a way to detect this without attempting to execute it?
Update: As @craq pointed out, shortly after this question was posted, there was an article about this on MATLAB Central: http://blogs.mathworks.com/loren/2013/08/26/what-kind-of-matlab-file-is-this/
Didn't find a clean solution, but you can probably use try-catch
(as @Ilya suggested) and nargin
EDIT - Use function
to avoid some naming conflict; use exist
to further classify the input (e.g. MEX-file)
function is_script = is_a_script( varargin )
% is_a_script( varargin ) returns one of the following:
% 1: if the input is a script
% 0: if the input is a function
% -1: if the input is neither a function nor a script.
is_script = 0;
switch( exist(varargin{1}) )
case 2
% If the input is not a MEX or DLL or MDL or build-in or P-file or variable or class or folder,
% then exist() returns 2
try
nargin(varargin{1});
catch err
% If nargin throws an error and the error message does not match the specific one for script, then the input is neither script nor function.
if( strcmp( err.message, sprintf('%s is a script.',varargin{1}) ) )
is_script = 1;
else
is_script = -1;
end
end
case {3, 4, 5, 6} % MEX or DLL-file, MDL-file, Built-in, P-file
% I am not familiar with DLL-file/MDL-file/P-file. I assume they are all considered as functions.
is_script = 0;
otherwise % Variable, Folder, Class, or other cases
is_script = -1;
end
这篇关于以编程方式区分脚本和函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!