我已将 perl.m 调整为 python.m 并将其附上以供其他人参考,但我似乎无法从 Python 脚本中获得任何输出以返回到 MATLAB 变量:(
这是我的 M 文件;请注意,我在代码中直接指向 Python 文件夹 C:\python27_64,这会在您的系统上发生变化。
function [result status] = python(varargin)
cmdString = '';
for i = 1:nargin
thisArg = varargin{i};
if isempty(thisArg) || ~ischar(thisArg)
error('MATLAB:python:InputsMustBeStrings', 'All input arguments must be valid strings.');
end
if i==1
if exist(thisArg, 'file')==2
if isempty(dir(thisArg))
thisArg = which(thisArg);
end
else
error('MATLAB:python:FileNotFound', 'Unable to find Python file: %s', thisArg);
end
end
if any(thisArg == ' ')
thisArg = ['"', thisArg, '"'];
end
cmdString = [cmdString, ' ', thisArg];
end
errTxtNoPython = 'Unable to find Python executable.';
if isempty(cmdString)
error('MATLAB:python:NoPythonCommand', 'No python command specified');
elseif ispc
pythonCmd = 'C:\python27_64';
cmdString = ['python' cmdString];
pythonCmd = ['set PATH=',pythonCmd, ';%PATH%&' cmdString];
[status, result] = dos(pythonCmd)
else
[status ignore] = unix('which python'); %#ok
if (status == 0)
cmdString = ['python', cmdString];
[status, result] = unix(cmdString);
else
error('MATLAB:python:NoExecutable', errTxtNoPython);
end
end
if nargout < 2 && status~=0
error('MATLAB:python:ExecutionError', ...
'System error: %sCommand executed: %s', result, cmdString);
end
编辑:
解决了我的问题,原来的 perl.m 通过更新 PATH 然后调用 Perl 指向 MATLAB 文件夹中的 Perl 安装。上面的函数指向我的 Python 安装。当我调用我的function.py 文件时,它位于不同的目录中并调用了该目录中的其他文件。这些没有反映在 PATH 中,我不得不将我的 Python 文件轻松安装到我的 Python 发行版中。