matlab调用Python的.py脚本文件

matlab把所有参数输出到一个文件里,然后用system命令调python脚本。python脚本读文件做计算结果再写文件。最后matlab再读文件得到结果。假设python脚本的用法是:

python xxx.py in.txt out.txt
则matlab调用的命令:

[status, cmdout] = system('python xxx.py in.txt out.txt')
Matlab的system函数用来向操作系统发送一条指令,并得到控制台的输出,可以直接将控制台的输出在Command Window打印出来,或者保存在变量中。 与system类似的还有dos函数和unix函数,我觉得它们都是对system函数的一种包装,而Matlab的system函数也许是对C的库函数system的包装。

先编写一个调用Python脚本的matlab程序即python.m

function [result status] = python(varargin)
% call python
%命令字符串
cmdString='python';
for i = 1:nargin
    thisArg = varargin{i};
    if isempty(thisArg) | ~ischar(thisArg)
        error(['All input arguments must be valid strings.']);
    elseif exist(thisArg)==2
        %这是一个在Matlab路径中的可用的文件
        if isempty(dir(thisArg))
            %得到完整路径
            thisArg = which(thisArg);
        end
    elseif i==1
        % 第一个参数是Python文件 - 必须是一个可用的文件
        error(['Unable to find Python file: ', thisArg]);
    end
    % 如果thisArg中有空格,就用双引号把它括起来
    if any(thisArg == ' ')
          thisArg = ['"', thisArg, '"'];
    end
    % 将thisArg加在cmdString后面
    cmdString = [cmdString, ' ', thisArg]
end
%发送命令
[status,result]=system(cmdString);
end
就可以用这个函数调用python脚本了。 下面就来个调用python脚本matlab_readlines.py(保存在matlab当前目录)的例子

import sys
def readLines(fname):
    try:
        f=open(fname,'r')
        li=f.read().splitlines()
        cell='{'+repr(li)[1:-1]+'}'
        f.close()
        print cell
    except IOError:
        print "Can't open file "+fname
if '__main__'==__name__:
    if len(sys.argv)<2:
        print 'No file specified.'
        sys.exit()
    else:
        readLines(sys.argv[1])
这个脚本用来读取一个文本文件,并生成Matlab风格的cell数组的定义字符串,每个单元为文本的一行。 放了一个测试用的文本文件test.txt在Matlab的Current Directory中,内容如下:

This is test.txt 

It can help you test python.m 

and matlab_readlines.py

测试:

在Matlab的Command Window中输入: 

>> str=python('matlab_readlines.py','test.txt'); 

>> eval(['c=' str]) 

c = 

'This is test.txt' [1x29 char] [1x23 char] 

>> celldisp(c) 

c{1} = This is test.txt 

c{2} = It can help you test python.m 

c{3} = and matlab_readlines.py

  • 9
    点赞
  • 70
    收藏
    觉得还不错? 一键收藏
  • 5
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 5
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值