簡體   English   中英

如何從python中捕獲matlab函數的輸出

[英]How to catch output of a matlab function from python

我正在運行下面的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功能。 “均值”函數只是一個例子。

使用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

注意,從Python調用時要分配x ; 腳本共享相同的堆棧。 (切記不要在調用者腳本中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讀取這個文件。 應該定義一個雙方互相交談的協議。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM