使用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 变量中