【问题标题】:How to catch output of a matlab function from python如何从python捕获matlab函数的输出
【发布时间】:2014-07-31 04:16:19
【问题描述】:

我正在运行下面的 python 代码来评估数组的平均值:

def matlab_func1(array):
    p = os.popen('matlab -nodesktop -nosplash  -r "mean('+str(array)+');exit"')
    while 1:
        line = p.readline()
        if not line:
            break
        print line

matlab_func1([1,2,3]) 

从下面的matlab脚本可以看出输出返回y。我想从 python 中捕获这个输出。

function y = mean(x,dim)
...
...
end

该解决方案必须适用于其他 matlab 函数。 'mean' 函数只是一个例子。

【问题讨论】:

  • 您的代码格式不正确。您必须使用四个空格来创建一个代码块,然后再使用四个空格来缩进函数内部的代码等。
  • 您是否考虑过使用例如pymatlab?
  • @Marcin 我安装了 pymatlab,但是找不到任何教程来了解它是如何工作的。 pymatlab 上的短脚本没有说明如何调用特定的函数。

标签: python matlab command-line


【解决方案1】:

使用fprintf 将需要的文本写入stderr。只需在开头添加一个额外的参数2

import subprocess
import os
def matlab_func1(array):
    p = subprocess.Popen(['/home/user/Matlab/bin/matlab', '-nodesktop', '-nosplash', '-r "m = mean(' + str(array) + ');fprintf(2, \'%d\\n\',m);exit" >/dev/null'], stdout=subprocess.PIPE, stderr=subprocess.PIPE)
    while 1:
        try:
            out, err = p.communicate()
        except ValueError:
            break
        print 'hello' + err

matlab_func1('[1,2,3]') 

需要注意的几点:

  • 将 Python 命令更改为 subprocess.Popen,它允许 stderr 管道。
  • 在 Matlab 命令中,使用fprintf 将想要的信息写入stderr。这可以将代码输出与 Matlab 的标题行分开。
  • 回到 Python,使用 Popen.communicate() 捕获 stderr 输出。
  • ValueError 异常处理 Matlab 的退出事件(p 已关闭)。

编辑:

对于提供多个输出的函数

假设一个 Matlab 函数是

function [y, z] = foo(x)
    y = x+1;
    z = x*20;
end

重点是使用fprintf 来抛出输出,同时像在Matlab 中通常那样做所有其他事情。

方法 1 - 内嵌脚本

p = subprocess.Popen(['/home/user/Matlab/bin/matlab', '-nodesktop', '-nosplash', '-r "[y, z] = foo(' + str(array) + ');for ii=1:length(y) fprintf(2, \'%d %d\\n\',y(ii),z(ii)); end; exit" >/dev/null'], stdout=subprocess.PIPE, stderr=subprocess.PIPE)

方法 2 - 独立脚本

首先新建一个caller.m脚本

[y, z] = foo(x);
for ii=1:length(y)
    fprintf(2, '%d %d\n',y(ii),z(ii));
end

注意x是Python调用时要赋值的;脚本共享相同的堆栈。 (记住不要clear调用者脚本中的工作区。)

然后,从 Python 调用脚本

p = subprocess.Popen(['/home/user/Matlab/bin/matlab', '-nodesktop', '-nosplash', '-r "x=' + str(array) + ';caller; exit" >/dev/null'], stdout=subprocess.PIPE, stderr=subprocess.PIPE)

将 Matlab 结果存储在 Python 变量中

  • 当通过stdout/stderr管道传递数据时:

    请参阅thissubprocess.check_output()

  • 在处理double 或二进制等严肃数据时:

    使用 Matlab 将数据写入外部文件。然后用 Python 读取这个文件。应该定义双方相互交谈的协议。

【讨论】:

  • 如果是文件怎么办?
  • @yasin.yazici 什么是“它”?
  • 如果函数的输出是文件怎么办?
  • 上面的代码报错:ValueError: I/O operation on closed file我刚刚改了matlab路径
  • 您的意思是输出数据存储在文件中,还是您的函数的输出是包含文件路径的字符串?我不明白你如何让函数输出一个“文件”。
猜你喜欢
  • 1970-01-01
  • 2013-05-10
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2014-09-11
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多