使用MATLAB脚本调用Python

2024-10-04 01:35:58 发布

您现在位置:Python中文网/ 问答频道 /正文

我是Python新手,我想把我的matlab变量传递给Python。下面的代码接受python脚本和参数。例如:python('square.py', '5')。可以通过这个matlab脚本把变量传递给Python吗?例如:

python('square.py', 'value')
function [result status] = python(varargin)

cmdString = '';

% Add input to arguments to operating system command to be executed.
% (If an argument refers to a file on the MATLAB path, use full file path.)
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
        % This is a valid file on the MATLAB path
        if isempty(dir(thisArg))
            % Not complete file specification
            % - file is not in current directory
            % - OR filename specified without extension
            % ==> get full file path
            thisArg = which(thisArg);
        end
    else
        % First input argument is PythonFile - it must be a valid file
        error('MATLAB:python:FileNotFound', 'Unable to find Python file: %s', thisArg);
    end
end

  % Wrap thisArg in double quotes if it contains spaces
  if any(thisArg == ' ')
    thisArg = ['"', thisArg, '"'];
  end

  % Add argument to command string
  cmdString = [cmdString, ' ', thisArg];
end

% Execute Python script
errTxtNoPython = 'Unable to find Python executable.';

if isempty(cmdString)
  error('MATLAB:python:NoPythonCommand', 'No python command specified');
   elseif ispc
  % PC
  pythonCmd = '/usr/bin/python';
  cmdString = ['python', cmdString];
  pythonCmd = ['set PATH=',pythonCmd, ';%PATH%&' cmdString];
  [status, result] = dos(pythonCmd);
else
  % UNIX
  [status ignore] = unix('which python'); %#ok
  if (status == 0)
    cmdString = ['python', cmdString];
    [status, result] = unix(cmdString);
  else
    error('MATLAB:python:NoExecutable', errTxtNoPython);
  end
end

% Check for errors in shell command
if nargout < 2 && status~=0
  error('MATLAB:python:ExecutionError', ...
    'System error: %sCommand executed: %s', result, cmdString);
end

Tags: topathinputifstatuserrorberesult
1条回答
网友
1楼 · 发布于 2024-10-04 01:35:58

对于少量的数字,基于您的代码,您可以编写基于printf的内容,基本上是通过格式化的数字字符串传递给python例程。python例程需要将其解析回数字。在

对于较大的数据垃圾,可以将其写入临时文件(可以是csv格式,也可以是带有fwrite的二进制文件)并传递文件名。如果您运行的是Linux,并且将/tmp挂载为tmpfs(比如ram磁盘),那么使用它作为临时存储可以加快进程。在

也有人在Python和Matlab之间使用UNIX管道。例如http://danapeerlab.googlecode.com/svn/trunk/freecell/depends/common/python/matlabpipe.py

相关问题 更多 >